gpt4 book ai didi

c# - 手动将 LINQ 查询语法转换为 Lambda 表示法

转载 作者:行者123 更新时间:2023-12-02 04:31:45 27 4
gpt4 key购买 nike

我通常使用 lambda 表示法进行选择,但对连接感到沮丧。我使用 LINQPad 为自己设置了一个简单的练习。 LINQ 查询是:

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9};
List <int> studentsIdList = new List<int> {1,3,5,7,9};

var q =
from c in allStudents
join p in studentsIdList on c equals p into ps
from p in ps.DefaultIfEmpty()
where p == 0
select new { Student = c};


q.Dump();

它会产生预期的结果集2,4,6,8

然而,当我用 lambda 表示法将其写为:

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9};
List <int> studentsIdList = new List<int> {1,3,5,7,9};

var q =
allStudents
.GroupJoin(
studentsIdList,
m => allStudents,
n => studentsIdList,
(m, n) => new {allS = m, excS = n.DefaultIfEmpty(0)})
.Where(x => x.excS.SingleOrDefault () == 0)
.Select (x => x.allS);

q.Dump();

我得到的结果集为1,2,3,4,5,6,7,8,9

并且 LINQPad 不显示 lambda 转换。

两个问题:

  • 我的 lambda 查询出了什么问题?
  • 如何让 LINQPad 显示 lambda 翻译?

更新

使用下面的答案我能够纠正我的尝试

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9};
List <int> studentsIdList = new List<int> {1,3,5,7,9};

var q = allStudents
.GroupJoin(studentsIdList,
a => a, b => b,
(a, b) => new { Id = a, Present = b.DefaultIfEmpty() })
.Where(x => x.Present.Single() == 0)
.Select(x => x.Id);

q.Dump();

非常感谢。

最佳答案

第二个问题的答案是在源集合上调用 .AsQueryable() 。这允许 LINQPad 显示 C# 到 lambda 语法的翻译:

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9};
List <int> studentsIdList = new List<int> {1,3,5,7,9};
var q = from c in allStudents.AsQueryable()
join p in studentsIdList on c equals p into ps
from p in ps.DefaultIfEmpty()
where p == 0
select new { Student = c};

q.Dump();

关于c# - 手动将 LINQ 查询语法转换为 Lambda 表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892624/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com