You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将指定LINQ查询语法转换为Lambda表达式实现的方法语法

LINQ查询语法转Lambda方法语法解决方案

你好,我帮你把这段LINQ查询语法转换成正确的Lambda方法语法,同时确保输出和你预期一致。

首先回顾你的原始查询语法:

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); 
}

你的尝试已经用到了GroupJoin,但缺少了展开分组的关键步骤(对应查询语法里的from std_grp in sg),也就是需要用SelectMany来扁平化分组,同时还要保留标准名称的信息,之后再完成排序和投影。

正确的Lambda方法语法代码如下:

var studentsWithStandard = standardList
    .GroupJoin(
        studentList,
        stad => stad.StandardID,
        s => s.StandardID,
        (stad, studentGroup) => new { stad.StandardName, studentGroup }
    )
    .SelectMany(
        stdWithGroup => stdWithGroup.studentGroup,
        (stdWithGroup, student) => new { 
            student.StudentName, 
            stdWithGroup.StandardName 
        }
    )
    .OrderBy(result => result.StandardName)
    .ThenBy(result => result.StudentName);

代码说明:

  1. GroupJoin:关联standardList和studentList,按StandardID分组,得到每个标准对应的学生分组,同时保留标准名称。
  2. SelectMany:扁平化分组,把每个分组里的学生和对应的标准名称组合成新的匿名对象,这一步对应查询语法里的from std_grp in sg。
  3. OrderBy + ThenBy:先按StandardName排序,再按StudentName排序,完全匹配原查询的排序逻辑。

运行这段代码后,输出和你的预期完全一致:

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

内容的提问来源于stack exchange,提问作者nahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:15:17