【问题标题】:Converting LINQ query syntax to Lambda notation manually手动将 LINQ 查询语法转换为 Lambda 表示法
【发布时间】:2014-04-06 10:11:21
【问题描述】:

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

非常感谢。

【问题讨论】:

    标签: c# linq lambda linqpad


    【解决方案1】:

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

    【讨论】:

      【解决方案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 问题,因为我自己不使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-23
        相关资源
        最近更新 更多