2012-08-07 37 views
0

我有兩個int值的形式的項目列表,名爲basketId,ProductNameId,它們已被選中並保留。例如{{1,1} {1,2},{1,3}}到一些上層basketId {{n,2} {n,6},{n,6},{n,6},{ N,7},{N,8}}。籃子的數量會有所不同,每個籃子的入場數量可能會有所不同。LINQ組合並獲得不同的最大發生次數

我需要輸出的形式爲ProductNameId和Max Count,用於存在於所有籃子集合中的每個ID。對於上面顯示的這兩個,這將是: 1,1,2,1,3,1,6,3,7,1,8,1,

我有以下代碼,它的工作原理,但它看起來很醜陋,囉嗦,所以我要求一點幫助,想出一個更好的方法/更簡潔 - 也許單一的陳述,也是如此。

// Get all the baskets that have been saved 
var baskets = Baskets.Where(x => x.MarketId == 1); 

// Group and get count for each product in each basket 
var counts = from q1 in all 
group q1 by new 
{ 
    q1.ProductNameId, 
    q1.BasketId 
} 
into g 
select new 
{ 
    ProductNameId = g.Key.ProductNameId, 
    Count = g.Count() 
}; 

// Group products and find the Maximum count that exists 
var max = from q2 in counts 
group q2 by q2.ProductNameId 
into g 
select new 
{ 
    ProductNameId = g.Key, 
    Max = g.Max (x => x.Count) 
}; 

// The distinct set of values present 
var distinct = max.Distinct(); 
+0

你能澄清你的數據嗎?它基本上是'List '哪裏籃子有'ProductNameId'和'BasketId'兩個整數?而且,如果是這樣,一些示例數據是什麼樣的,你想從中得到什麼? – 2012-08-07 14:01:54

+0

因此,例如,如果你有這樣的:{{ 1,1}, {1,2}, {1,3}, {1,2}, {1,3},{ 2,2 }, {2,3}, {1,4}, {1,5} }你會期待這個結果:? {ProductNameId = 1,Max = 1},{ProductNameId = 2,Max = 3},{ProductNameId = 3,Max = 3},{ProductNameId = 4,Max = 1},{ProductNameId = 5,Max = 1}, – eburgos 2012-08-07 14:09:14

+0

籃子基本上是一個有兩列的產品,BasketId(購物籃有內容)和ProductNameId(產品類型已被購買)。在任何一天中都有數百個獨特的BasketId記錄,並且對於每個不同的BasketId值,通常有5到50個ProductNameId值。當客戶購買多種相同產品類型時,其中一些值會出現一次以上。他們可以例如購買兩種不同的麥片或糖果,籃子將包含兩個記錄 – 2012-08-09 04:33:35

回答

0

基礎數據還是有點神祕的給我,但你的代碼看起來像,我相信你正在試圖做到這一點:

// Get all the baskets that have been saved 
var baskets = Baskets.Where(x => x.MarketId == 1); 

// Group and get count for each product in each basket 
var distinct = from q1 in baskets 
    group q1 by q1.ProductNameId into g 
    select new 
    { 
     ProductNameId = g.Key, 
     Max = (from q2 in g 
      group q2.BasketId by q2.BasketId).Max (x => x.Count()) 
    }; 
+0

感謝布拉德,那確實是... – 2012-08-09 04:34:51

0

這裏做一個非常直接的方式它:

var query = 
    baskets 
     .ToLookup(b => b.ProductNameId) 
     .Select(l => new 
     { 
      ProductNameId = l.Key, 
      Max = l.Count(), 
     }); 
+0

對不起,但是這不能正常工作。此處生成的最大值實際上包含處理的所有籃子中ProductNameId的計數。當我在樣本上運行它時,生成的最大值是132個產品,其中productNameId == 1,它是所有籃子中ProductNameId == 1值的總數。任何一個籃子中存在的ProductNameId == 1的實際最大數量是3.我需要此值而不是所有籃子中存在的計數。 – 2012-08-13 06:31:30