请求将指定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);
代码说明:
- GroupJoin:关联
standardList和studentList,按StandardID分组,得到每个标准对应的学生分组,同时保留标准名称。 - SelectMany:扁平化分组,把每个分组里的学生和对应的标准名称组合成新的匿名对象,这一步对应查询语法里的
from std_grp in sg。 - 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
相关产品推荐
相关产品推荐

