LINQ: select everything from each group except the first item

It is easy to choose the first of each group:

var firstOfEachGroup = dbContext.Measurements .OrderByDescending(m => m.MeasurementId) .GroupBy(m => new { m.SomeColumn }) .Where(g => g.Count() > 1) .Select(g => g.First()); 

But...
Question : how can I select everything from each group except the first element?

  var everythingButFirstOfEachGroup = dbContext.Measurements .OrderByDescending(m => m.MeasurementId) .GroupBy(m => new { m.SomeColumn }) .Where(g => g.Count() > 1) .Select( ...? ); 

Additional Information:
My real goal is to remove all duplicates except the last one (in bulk, RemoveRange .: do not use the built-in foreach), so after the previous request I want to use RemoveRange :

  dbContext.Measurements.RemoveRange(everythingButFirstOfEachGroup); 

So, if my question does not make sense, this information may be convenient.

+5
source share
3 answers

Use Skip(1) to skip the first entry and select the rest.

Sort of:

 var firstOfEachGroup = dbContext.Measurements .OrderByDescending(m => m.MeasurementId) .GroupBy(m => new { m.SomeColumn }) .Where(g => g.Count() > 1) .SelectMany(g => g.OrderByDescending(r => r.SomeColumn).Skip(1)); 

See: Enumerable.Skip

If you don't need a flattened collection, replace SelectMany with Select in the code snippet.

+6
source

IGrouping<K, V> implements IEnumerable<V> ; you just need to skip inside the select clause to apply it to each group:

 .Select(g => g.Skip(1)) 
+2
source

You can always use .Distinct () to remove duplicates; presumably sorting or sorting by reverse, and then applying .distinct () will give you what you want.

0
source

Source: https://habr.com/ru/post/1212992/


All Articles