C # Remove "partial" duplicates from an array collection

I tried to find the answer for my problem, but I was stuck. I have a set of arrays and need to delete entries where some attributes are the same.

Example: I have attributes - BeginTime, EndTime, Date, Price.

07:00, 11:00, 2011-11-14, 90 08:00, 12:00, 2011-11-14, 110 07:00, 11:00, 2011-11-15, 120 07:00, 11:00, 2011-11-14, 50 

And I want to delete records where BeginTime, EndTime and Date are the same, and the price is not the lowest. In this example, the deleted record will be the first.

Thanks for any help or suggestion.

+4
source share
1 answer

As with LINQ:

 IEnumerable<Bar> bars = ... var lowestPriceBars = bars.GroupBy(bar => new { bar.BeginTime, bar.EndTime, bar.Date } ) .Select(g => g.OrderBy(bar => bar.Price).First()) .ToArray(); 

This works by grouping items with the same timestamps together, and then creating the lowest cost item from each group. Please note: if there are several elements in a group with the same minimum price, the request will save one of them arbitrarily.

Also note that with the MinBy operator (for example, one of the more morelinq ) you can make the Select operation more efficiently with:

 .Select(g => g.MinBy(bar => bar.Price)) 

EDIT . If you want to keep all items with the lowest price, you can do:

 var lowestPriceBars = bars.GroupBy(bar => new { bar.BeginTime, bar.EndTime, bar.Date }) .SelectMany(timeGroup => timeGroup .GroupBy(bar => bar.Price) .OrderBy(priceGroup => priceGroup.Key) .First()) .ToArray(); 
+6
source

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


All Articles