2015-04-08 133 views
1

我有一个可以存放库存项目的表格。这些股票项目具有以下属性如何将左连接加入到另一个左连接

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 
+0

我认为你可以找到适合在这里你的问题的详细信息:HTTP:/ /stackoverflow.com/questions/448203/linq-to-sql-using-group-by-and-countdistinct – Matheno

回答

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), 
      } 
+0

非常感谢您的帮助。但是如果我使用多个带有内连接和外连接的表,并且我需要同时对来自多个表/对象的参数进行分组呢? – user4591106

+0

@ user4591106请更新您的问题,详细解释您的情况。 –

+0

更多关于这个问题的工作和广泛的搜索我已经找到了下一个问题的解决方案。但我很感谢你的进一步帮助。非常感谢你。 – user4591106