2015-04-08 135 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