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 |
__________________________
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With