Procedure when using Distinct () for a collection

If my collection is ordered by date, will Distinct () take the first object in the list of neighboring duplicates, or not sure? I use IEqualityComparer, which does not take into account the date field, but I want to be sure that the latest date is always accepted.

+3
source share
4 answers

You should use GroupBy:

from s in whatever
group s by new { s.Field1, s.Field2 } into g
select g.OrderByDescending(o => o.Date).First()

EDIT . You can also use IEqualityComparerwith GroupBy:

whatever.GroupBy(
    s => s,      //Key
    g => g.OrderByDescending(o => o.Date).First()  //Result
    new MyComparer()
);
+5
source

Not defined what is required.

In practice, this is likely to take first place if you use LINQ for objects, but should not rely on it.

, , .. , .

, DistinctBy morelinq Jon Skeet .

+2

, Enumerable.Distinct. , , , .

+1

Enumerable.Distinct , , , -, . , undefined, , .

I usually don't like relying on unspecified behavior, but I find it highly unlikely that this will change. This is a natural behavior from saving a set of what you have already returned, and getting the result as soon as you see a new element.

If you want to rely on this unspecified behavior, Distinctyou must order items by date (descending) before using . In addition, you can use grouping and then arrange each group accordingly.

+1
source

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


All Articles