代码之家  ›  专栏  ›  技术社区  ›  netwire

将两个LINQ合并为一个调用

  •  2
  • netwire  · 技术社区  · 14 年前

    我使用两个类似的LINQ查询返回结果,唯一的区别是where子句( && s.OptIn == "Yes"

    而不是

    A   2 
    B   3
    

    另一个结果是

    A 1
    B 1
    

    A   2   1 
    B   3   1
    

    这是林肯:

            var result = from s in pdc.ScanLogs
                         from e in pdc.Exhibits
                         from ce in pdc.ClientEvents
                         where s.ExhibitID == e.ExhibitID
                         && e.ClientEventID == ce.ClientEventID
                         group 1 by new { ce.EventID } into d
                         select new {
                             EventID = d.Key.EventID,
                             Count = d.Count()
                         };
    
            var result = from s in pdc.ScanLogs
                         from e in pdc.Exhibits
                         from ce in pdc.ClientEvents
                         where s.ExhibitID == e.ExhibitID
                         && e.ClientEventID == ce.ClientEventID
                         && s.OptIn == "Yes"
                         group 1 by new { ce.EventID } into d
                         select new {
                             EventID = d.Key.EventID,
                             Count = d.Count()
                         };
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Anthony Pegram    14 年前

    您可以在Count方法中提供谓词。示例如下:

    List<int> list = new List<int> { 1, 2, 3, 4, 5 };
    var counts = new { CountAll = list.Count(), CountEven = list.Count(i => i % 2 == 0) };
    Console.WriteLine(counts.CountEven);
    

    为Linq向实体编写的类似查询也可以工作并生成工作SQL。

    我还没有完全重建你的样品,但你应该可以重做成这样。

    var result = from s in pdc.ScanLogs
                    from e in pdc.Exhibits
                    from ce in pdc.ClientEvents
                    where s.ExhibitID == e.ExhibitID
                    && e.ClientEventID == ce.ClientEventID
                    group new { s, e, ce } by new { ce.EventID } into d
                    select new
                    {
                        EventID = d.Key.EventID,
                        Count = d.Count(),
                        CountOptIn = d.Count(item => item.s.OptIn == "Yes")
                    }; 
    
        2
  •  1
  •   Codism    14 年前
    IQueryable<ScanLog> scanlogs = pdc.ScanLogs;
    if (filter) scanlogs = scanlogs.Where(...);
    var result = from s in scanlogs
       ...