首页 > 解决方案 > 有人可以使用 lambda 将以下 linq 查询语法转换为方法语法吗?

问题描述

IList<Student> studentList = new List<Student>() { 
        new Student() { StudentID = 1, StudentName = "John", Age = 18, StandardID = 1 } ,
            new Student() { StudentID = 2, StudentName = "Steve",  Age = 21, StandardID = 1 } ,
            new Student() { StudentID = 3, StudentName = "Bill",  Age = 18, StandardID = 2 } ,
            new Student() { StudentID = 4, StudentName = "Ram" , Age = 20, StandardID = 2 } ,
            new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 } 
    };

    IList<Standard> standardList = new List<Standard>() { 
        new Standard(){ StandardID = 1, StandardName="Standard 1"},
        new Standard(){ StandardID = 2, StandardName="Standard 2"},
        new Standard(){ StandardID = 3, StandardName="Standard 3"}
    };

    var studentsWithStandard = from stad in standardList
                       join s in studentList
                       on stad.StandardID equals s.StandardID
                       into sg
                           from std_grp in sg 
                           orderby stad.StandardName, std_grp.StudentName 
                           select new { 
                                            StudentName = std_grp.StudentName, 
                                            StandardName = stad.StandardName 
                            };

foreach (var group in studentsWithStandard)
    {
        Console.WriteLine("{0} is in {1}", group.StudentName, group.StandardName);
    }

我试过了。我的代码如下。

 var studentsWithStandard  = standardList.GroupJoin(studentList, stand => stand.StandardID, s => s.StandardID,
            (stand, students) => new {StandardName = stand.StandardName, studentGroup = students}).OrderBy(an => an.StandardName);

输出将是这样的:

John is in Standard 1
Steve is in Standard 1
Bill is in Standard 2
Ram is in Standard 2

我从http://www.tutorialsteacher.com/codeeditor?cid=cs-JUmITE得到它 提前谢谢。

标签: c#linqlambda

解决方案


根据我的经验join,查询语法比 lambda 语法更具可读性的一个地方,但无论如何......

我强烈推荐阅读 Jon Skeet 的优秀书籍 C# In Depth。LINQ 的章节非常清楚地解释了各种查询语法的含义。https://www.manning.com/books/c-sharp-in-depth-third-edition

join只有一个的表达式from将转换为Join方法,而不是GroupJoin. GroupJoin在 . 前面有两个froms 时使用join

你会希望它做一个内部连接:

standardList
    .Join(studentList,
        stad => stad.StandardID,
        s => s.StandardID,
        (stad, s) => new { Standard = stad, Student = s })
    .OrderBy(x => x.Standard.StandardName)
    .ThenBy(x => x.Student.StudentName)

推荐阅读