Wednesday, September 27, 2017

Linq- Difference between Select and SelectMany



Suppose we have a “Student” class and a “Subject” Class.
Student class has a  public List<string> Subjects { get; set; }   property.
new Student
            {
                Name = "Tom",
                Gender = "Male",
                Subjects = new List<string> { "ASP.NET", "C#" }
            },


Now, to print all the subjects using the “Select” method
The “Select” method returns a List of List<string>, so we have to use two nested foreach loops to print the subjects.

IEnumerable<List<string>> result = Student.GetAllStudetns().Select(s => s.Subjects);
foreach (List<string> stringList in result)
{
    foreach (string str in stringList)
    {
        Console.WriteLine(str);
    }
}



The “SelectMany()” method on the other hand, flattens the queries that return lists of lists into a single list.
So, for above example, If we use SelectMany() to print all the subjects of students, then we have to use just one foreach loop. i.e.

IEnumerable<string> result = Student.GetAllStudetns().SelectMany(s => s.Subjects);
  foreach (string str in result)
     {
        Console.WriteLine(str);
     }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More