Linq query to select the best entries

I have an IEnumerable<MyData> that contains the 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 the top two lines of Linq according to type name

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

Jay and Vik have the top two sums, so I need these records

 Fruits | Name | Quantity | __________________________ Mango | Jay | 10 | __________________________ Apple | Jay | 16 | __________________________ Grapes| Jay | 12 | __________________________ Mango | Vik | 20 | __________________________ Apple | Vik | 15 | __________________________ 
+8
c # linq
source share
4 answers

It looks like you might need 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); 

This will take the first two groups, so you will 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); } } 
+11
source share

Something like this will work.

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

Step by step

  • Group by name (like what you summarize)
  • Sort by sum of values
  • Take the 2 upper names
  • Select items from the source list matching these names.
+4
source share

Try the following:

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

It should look like this:

 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)); 
0
source share

All Articles