如何离开加入另一个左连接

时间:2015-04-08 10:48:29

标签: c# linq entity-framework group-by

我有一张包含库存商品的表格。这些库存商品具有以下属性

public class StockItem
{
    public int BrandId { get; set; }
    public int ModelId { get; set; }
    public decimal Price { get; set; }
    public int StoreId { get; set; }
}

StoreId可以是1(商店A )或2(商店B

我想将这些项目分组以获得以下结果

BrandId
ModelId
Count in Store A
count in Store B

我之前使用过group by子句但不是这样。我该如何编写linQ语句来完成我的任务?

总结一下,我有以下记录

Id   BrandId   ModelId   Price   StoreId
=========================================
1       1         1       11        1
2       1         1       11        1
3       1         2       12        1
4       1         2       12        2
5       1         1       11        2

并尝试获得以下结果

BrandId   ModelId   CountInStoreA   CountInStoreB
=================================================
    1        1            2               1
    1        2            1               1

1 个答案:

答案 0 :(得分:3)

var result = from item in db.Items
          group item by new { item.BrandId, item.ModelId, item.TotalPrice }
          into gr
          select new 
          {
              gr.Key.BrandId,
              gr.Key.ModelId,
              gr.Key.TotalPrice,
              CountA = gr.Count(it => it.StoreId == 1),
              CountB = gr.Count(it => it.StoreId == 2),
          }