我有兩個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();
你能澄清你的數據嗎?它基本上是'List'哪裏籃子有'ProductNameId'和'BasketId'兩個整數?而且,如果是這樣,一些示例數據是什麼樣的,你想從中得到什麼? –
2012-08-07 14:01:54
因此,例如,如果你有這樣的:{{ 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
籃子基本上是一個有兩列的產品,BasketId(購物籃有內容)和ProductNameId(產品類型已被購買)。在任何一天中都有數百個獨特的BasketId記錄,並且對於每個不同的BasketId值,通常有5到50個ProductNameId值。當客戶購買多種相同產品類型時,其中一些值會出現一次以上。他們可以例如購買兩種不同的麥片或糖果,籃子將包含兩個記錄 – 2012-08-09 04:33:35