2016-11-29 31 views
4

嗨,大家好,我有一個關於Linq的問題。csharp羣問題

我將結果分組在顧客郵政編碼上。對於每個郵政編碼,我希望看到訂購的金額和訂購的設備數量。

到目前爲止,我的代碼如下所示:

var statistics = from b in db.Bookings 
       from c in db.Customers 
       where b.customerID == c.id 
       group c by c.zipcode into stat 
       select new { 
           Zipcode = stat.Key, 
           NumberOfBookings = stat.Count() 
          }; 

此碼組結果放入拉鍊碼,給我預訂量在每個郵編。如何獲得設備數量?

回答

2

而不是使用join就像在SQL中,你可以(而且最好)使用導航屬性從你的模型:

var statistics = 
    from b in db.Bookings 
    group b by b.Customer.zipcode into g 
    select new 
    { 
     Zipcode = g.Key, 
     NumberOfBookings = g.Count(), 
     NumberOfEquipments = g.SelectMany(b => b.Equipments).Count(), 
    }; 

注意,g變量代表用相同的一組預定的郵政編碼,因此在應用Count運營商之前,使用SelectMany獲取所有相關設備。

當然,這不是唯一的方法,例如,你可以使用Sum代替:

NumberOfEquipments = g.Sum(b => b.Equipments.Count())