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

亚音速3和Linq Group By With Count

  •  1
  • Yogesh  · 技术社区  · 15 年前

    我有以下两张表:

    Customer
    {
    int Id
    int Name
    }
    
    Bills
    {
    int Id
    int CustomerId
    decimal Amount
    bool IsDue
    }
    

    现在我正试图得到一个列表,其中包括:

    1. 每个客户的关联账单计数条目。
    2. 在ISDUE为真的情况下,为每一个客户记录相关账单的数量。

    我试着做第一个这样的:

    var results = from c in _db.Customers
                  join b in _db.Bills on c.Id equals b.CustomerId into j1
                  from j2 in j1
                  group j2 by c.Id into grouped
                  select new
                      {
                          CustomerId = grouped.Key, 
                          NoOfBills = grouped.Count()
                      };
    

    这将引发一个错误: 类型为“System.Collections.Generic.IEnumerable”的表达式 1[OutstandingMonitor.MonitorData.Customer]' cannot be used for parameter of type 'System.Linq.IQueryable 1[未结监控.监控数据.客户]……

    请帮我解决这个问题。

    此外,这两个查询可以合并吗?

    PS:使用亚音速3.0.0.3和ActiveRecord

    2 回复  |  直到 15 年前
        1
  •  1
  •   Yogesh    15 年前

    我找到了一个不那么有效的解决方案(如果它确实有效,我很乐意知道…:p)。这里是:

    var results = from d in _db.Bills
              group d by d.CustomerId into g
              select new
              {
                  CustomerId = g.Key,
                  NoOfBills = g.Count()
              };
    
    var results2 = from c in _db.Customers
               join r in results on c.Id equals r.CustomerId
               select new
               {
                   CustomerId = r.CustomerId,
                   CustomerName = c.Name,
                   City = c.City,
                   NoOfBills = r.NoOfBills
               };
    

    就目前而言,它工作得很好。

        2
  •  0
  •   Keith    15 年前

    无论您在何处使用“客户关联账单计数”的值,您都不能在LINQ中简单地执行此操作(但是,如果您在DBML中设置了适当的关系,这将仅起作用):

    var customers = _db.Customers; // Not necessary, but here for clarity
    
    // ... more code
    
    // Access the number of bills for each customer:
    
    foreach (var customer in customers)
    {
        int totalBills = customers.Bills.Count();
        int totalDueBills customers.Bills.Where(b => b.IsDue).Count();
    }