代码之家  ›  专栏  ›  技术社区  ›  Peter Smith

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

  •  2
  • Peter Smith  · 技术社区  · 12 年前

    我通常使用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 回复  |  直到 12 年前
        1
  •  3
  •   Wasif Hossain    12 年前

    第二个问题的答案是打电话 .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
  •  2
  •   voidengine    12 年前

    这是如何编写联接的:

    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问题,因为我自己不会使用它。

    推荐文章