2011-12-22 172 views
8

我有IEnumerable<MyData>其中包含以下數據Linq查詢選擇最前的記錄

Fruits | Name | Quantity | 
__________________________ 
Mango | Jay | 10 | 
__________________________ 
Apple | Jay | 16 | 
__________________________ 
Grapes| Jay | 12 | 
__________________________ 
Mango | Raj | 11 | 
__________________________ 
Apple | Raj | 20 | 
__________________________ 
Grapes| Raj | 3  | 
__________________________ 
Mango | Vik | 20 | 
__________________________ 
Apple | Vik | 15 | 
__________________________ 

我需要從LINQ的頂部根據名稱的兩個量等來選擇

Jay (10+16+12) = 38 
Raj (11+20+3) = 34 
Vik (20+15) = 35 

周杰倫和維克具有前兩名量總和所以我需要這些記錄

Fruits | Name | Quantity | 
__________________________ 
Mango | Jay | 10 | 
__________________________ 
Apple | Jay | 16 | 
__________________________ 
Grapes| Jay | 12 | 
__________________________ 
Mango | Vik | 20 | 
__________________________ 
Apple | Vik | 15 | 
__________________________ 
+0

所以我只想澄清。你想總結每個名字的數量,找到最前面的兩個名字,然後選擇這些名字的記錄? – Ray

+0

@雷:是的。 –

回答

11

聽起來像是你可能想是這樣的:

var query = from item in collection 
      group item by item.Name into g 
      orderby g.Sum(x => x.Quantity) descending 
      select g; 
var topTwo = query.Take(2); 

這將需要前兩個,所以你用它作爲:

foreach (var group in topTwo) 
{ 
    Console.WriteLine("Name: {0}", group.Key); 
    foreach (var item in group) 
    { 
     Console.WriteLine(" {0}: {1}", item.Fruits, item.Quantity); 
    } 
} 
+1

謝謝!我的問題現在已經解決了。 –

+1

應該不是order by desc? – Ray

+2

@ Ray:是的 - Govind給我修好了;謝謝:) –

0

請嘗試以下操作:

var topTwo = myData.GroupBy(d => d.Name).OrderByDescending(g => g.Sum(d => d.Quantity)).TakeWhile((data,index) => index < 2).SelectMany(g => g); 
4

像這樣的東西會工作。

private static IEnumerable<MyData> GetTop2Names(IEnumerable<MyData> data) 
{ 
    var top2 = data.GroupBy(d => d.Name) 
        .OrderByDescending(g => g.Sum(d => d.Quantity)) 
        .Take(2) 
        .Select(g => g.Key); 
    return data.Where(d => top2.Contains(d.Name)); 
} 

一步

  1. 集團的名稱步驟(因爲這是你總結的)
  2. 排序數量
  3. 的總和取前2名
  4. 選擇來自原始列表的與這些名稱匹配的項目。
+0

+1非常好...非常感謝你 –

0

應該是這樣的:

IEnumerable<MyData> source = new List<MyData>(); 
var names = source 
    .GroupBy(item => item.Name) 
    .ToDictionary(item => item.Key, item => item.Sum(i => i.Quantity)) 
    .OrderByDescending(item => item.Value) 
    .Select(item => item.Key) 
    .Take(2); 

var result = source.Where(item => names.Contains(item.Name));