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

时间:2014-04-06 10:11:21

标签: c# linq lambda linqpad

我通常使用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

的结果集

AND 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();

非常感谢。

2 个答案:

答案 0 :(得分:3)

第二个问题的答案是在源集合上调用.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();

答案 1 :(得分:2)

这是您编写联接的方式:

var q = allStudents
    .GroupJoin(studentsIdList, a => a, b => b, (a, b) => new { Id = a, Present = b })
    .Where(join => !join.Present.Any())
    .Select(join => join.Id);

当然,对于这种情况,使用Except会更简单。

无法帮助解决Linqpad问题,因为我自己不会使用它。