Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to select top records

Tags:

c#

linq

I have IEnumerable<MyData> which contains following data

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    |
__________________________

I need to select from Linq top two quantity according to name like

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

Jay and Vik have top two quantity sum so I need these records

Fruits | Name | Quantity | 
__________________________
 Mango | Jay  |    10    |
__________________________
 Apple | Jay  |    16    |
__________________________
 Grapes| Jay  |    12    |
__________________________
 Mango | Vik  |    20    |
__________________________
 Apple | Vik  |    15    |
__________________________
like image 516
Govind Malviya Avatar asked Dec 22 '11 11:12

Govind Malviya


1 Answers

Sounds like you might want something like:

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);

That will take the first two groups, so you'd use it as:

foreach (var group in topTwo)
{
    Console.WriteLine("Name: {0}", group.Key);
    foreach (var item in group)
    {
        Console.WriteLine("  {0}: {1}", item.Fruits, item.Quantity);
    }
}
like image 123
Jon Skeet Avatar answered Sep 22 '22 00:09

Jon Skeet