Mar

22

LINQ Select vs SelectMany

Posted by 7 Comments

The best way to explain the difference between Select and SelectMany in Linq is to show an example. In this example we will return a list of courses, each containing a list of students. You will see that Select will return a list of lists of students while SelectMany will flatten the lists into a single list of students.


First our Course class:

class Course
    {
        public int courseId;
        public string courseName;
        public List<string> students;
    }

Then we’ll add a method to return a list of courses, each containing a list of multiple students:

static List<Course> GetCourses() {
    List<Course> courses = new List<Course> {
        new Course {
            courseId = 1,
            courseName = "Course 1",
            students =  new List<string> { "Student 1", "Student 2", "Student 3" }
        },
        new Course {
            courseId = 2,
            courseName = "Course 2",
            students = new List<string> { "Student A", "Student B", "Student C" }
        },
        new Course {
            courseId = 3,
            courseName = "Course 3",
            students = new List<string> { "Student X", "Student Y", "Student Z" }
        }
    };
    return courses;
}

Now when we try to list all students from each course using Select, you can see that Select returns three lists of students, one for each course:

var students = GetCourses().Select(c => c.students);
foreach (var s in students)
{
    Console.WriteLine(s.ToString());
}

Result:

System.Collections.Generic.List`1[System.String]
System.Collections.Generic.List`1[System.String]
System.Collections.Generic.List`1[System.String]

So we would need to iterate over each list of students to achieve the desired results.


However, SelectMany will flatten these list into a single result:

var students = GetCourses().SelectMany(c => c.students);
foreach (var s in students)
{
    Console.WriteLine(s.ToString());
}

Result:

Student 1
Student 2
Student 3
Student A
Student B
Student C
Student X
Student Y
Student Z

Category: .NET, C#, Development, Linq

Comments (7)

Trackback URL | Comments RSS Feed

  1. anonymous says:

    Nice explanation

  2. DMVC says:

    Simple and effective. Thanks

  3. MoRez says:

    Thanks, nice explanation!

  4. Riya Ram says:

    this is very good example

  5. Anonymous says:

    Bt what if I want to select course data in same query with select many

  6. mehmedju says:

    What if I do

    var students = GetCourses().Select(c => c.students).toList();

    Does this return same value as using SelectMany method?

Leave a Reply