How do lambda parameters work?

Say we have a Student class

class Student
{
    public string Name { get; set; }
    public string Gender { get; set; }
    public List<string> Subjects { get; set; }

    public static List<Student> GetAllStudetns()
    {
        List<Student> listStudents = new List<Student>
        {
           new Student
           {
               Name = "Tom",
               Gender = "Male",
               Subjects = new List<string> { "ASP.NET", "C#" }
           },
           new Student
           {
              Name = "Mike",
               Gender = "Male",
               Subjects = new List<string> { "ADO.NET", "C#", "AJAX" }
           }
        };

        return listStudents;
    }
}

And we want to print each student with topics like this:

Tom - ASP.NET

Tom - C #

Mike - ADO.NET

Mike - C #

etc.

so i found the answer

var result = Student.GetAllStudents().SelectMany(s => s.Subjects, (student, subject) => new { StudentName = student.Name, SubjectName = subject});

//then use foreach loop to retrieve...

I can understand the second use of =>, which is simply projecting onto an anonymous type. But I do not understand the first part

s => s.Subjects, (student, subject)

In my opinion, the left side => is the intput parameter, which is an instance of Student s in this case, but the right side => should be the return type associated with the Student s instance, for example s.Name if we want to get the student name, so What does it mean (student, subject)?

+4
source share
2 answers

SelectMany . . https://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx

s => s.Subjects - - ,

(student, subject) => new { StudentName = student.Name, SubjectName = subject} - - ,

+2

, Subjects List<string> , , -. (s => s.Subjects, (student, subject)) , .SelectMany

public static IEnumerable<TResult> SelectMany<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TResult>> selector
)

(Func) ( Student) IEnumerable, , List<string>.

, (student, subject) Student, s.Subjects, .SelectMany - .

(Tom - ASP.NET,C#), GroupBy . , - ;

: , :

var result = Student.GetAllStudents()
                    .GroupBy(s => s.Name)
                    .Select(x=> new { StudentName = x.Key, SubjectName = String.Join(",",
                   x.SelectMany(y=>y.Subjects)
                    .ToList()});
+2

Source: https://habr.com/ru/post/1665475/


All Articles