c# - 有人可以使用 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得到它 提前谢谢。
解决方案
根据我的经验join
,查询语法比 lambda 语法更具可读性的一个地方,但无论如何......
我强烈推荐阅读 Jon Skeet 的优秀书籍 C# In Depth。LINQ 的章节非常清楚地解释了各种查询语法的含义。https://www.manning.com/books/c-sharp-in-depth-third-edition
join
只有一个的表达式from
将转换为Join
方法,而不是GroupJoin
. GroupJoin
在 . 前面有两个from
s 时使用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)
推荐阅读
- go - Go 模板 - 范围的语法
- r - 在没有 NA 的情况下按组计算平均值
- swift - 如何在 Swift 中传递多个符合单个协议的泛型参数
- sql - 如何将多个值传递给 sys.objects 表中的“SCHEMA_ID”
- c++ - 使用头文件编译时对对象的未定义引用
- memory-leaks - 为什么 Netty ByteBuf.readBytes 会导致内存泄漏?
- python - Python,在一个文件中查找数字字符串,在另一个文件的行内匹配该字符串,并将第一个文件中的字符串替换为第二个文件中的行
- canvasjs - Canvasjs 堆叠条在一个完整条中按每个堆叠块值从高到低排序
- python - 将仪表板从 Excel 选项卡加载到 python 中失败
- python-3.x - NameError:名称“second_number”未在 tkinter 中定义