LINQ projection operators( Select and SelectMany)

No.of Views1942
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  20 Aug 2010 10:08:43
Tag : LINQ , Miscellaneous
Projection helps us developer to retrieve desired result from the collection . LINQ provides two projection operator. Select and SelectMany. Select works with one collection whereas SelectMany works with more than one collection
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Projection transforms the query result into the form defined by the developer. There are two projection operators in LINQ 

Image Loading

Let us say, there is a class 

Image Loading

And a function returning List<Student> as below, 

Image Loading

Select operator

Below query will return name and roll number of all the students. 

Image Loading

Output 

Image Loading

Below query will project name of the student’s starts with D. 

Image Loading

Output 

Image Loading

Above was very simple query let us modify the display function and try to display subject of the student 

Image Loading

Output 

Image Loading

If you notice the above output, we are not getting the proper output and it is saying that Subject is generic list. So to fetch we need to enumerate through the list.

Now question is how to retrieve all the subjects of students?

SelectMany

So to retrieve query from more than one collection SelectMany come into action. 

Image Loading

Above query will return the entire subjects of all the students.

Output 

Image Loading

The other way to apply SelectMany operator is directly apply on the retrieval query as below, 

Image Loading

Output 

Image Loading

Full Source code is as below,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication9
{class Program
    {static void Main(string[] args)
        {// Reteriving all students with name D var result1 = from r in GetStudents()
                          where r.Name.StartsWith("D")
                          select r;foreach (var r in result1)
            {
                Console.WriteLine(r.Name);
            }// Reteriving  the result in Anonymous  classvar result2 = from r in GetStudents()
                          select new { r.RollNumber, r.Name };foreach (var r in result2)
            {
                Console.WriteLine(r);
            }// Reteriving using SelectMany var result3 = from r in GetStudents()
                          select r;foreach (var r inresult3.SelectMany(Student => Student.Subject))
            {
                Console.WriteLine(r);
            }// directly applying  SelectMany var result = GetStudents().AsQueryable().SelectMany(Subject => Subject.Subject);foreach (var r in result)
            {
                Console.WriteLine(r);
            }        
           
            Console.Read();
        }static List<Student> GetStudents()
        {
            List<Student> students = new List<Student>{new Student { 
                                         Name = "Dhananjay",
                                         RollNumber ="1" ,
                                         Subject= new List<string>{"Math","Phy"}},new Student { 
                                         Name = "Scott",
                                         RollNumber ="2" ,
                                         Subject= new List<string>{"Che","Phy"}},new Student { 
                                         Name = "John",
                                         RollNumber ="3" ,
                                         Subject= new List<string>{"Hindi","Phy"}}};return students; 
        }

    }class Student
    {public string Name { get; set; }public string RollNumber { get; set; }public List<string> Subject { get; set; }
    }
}

 I hope this article was useful. Thanks for reading. Happy Coding

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date -20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top