Saturday 6 January 2018

Select and SelectMany: LINQ projection operator

public class Course
    {
        public int Id;
        public string Name;
        public List<string> students;
    }

public static List<Course> Get() {
    List<Course> c1 = new List<Course> {
        new Course {
          Id = 1,
            Name = "Course1",
            students =  new List<string> { "Student1", "Student2", "Student3" }
        },
        new Course {
            Id = 2,
            Name = "Course2",
            students = new List<string> { "StudentA", "StudentB", "StudentC" }
        },
        new Course {
            Id = 3,
           Name = "Course 3",
            students = new List<string> { "StudentX", "StudentY", "StudentZ" }
        }
    };
    return courses;
}

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


Result:

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


However, SelectMany

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

Student1
Student2
Student3
StudentA
StudentB
StudentC
StudentX
StudentY
StudentZ

No comments:

Post a Comment