Tell LINQ Distinct which item to return

I understand how to make Distinct () in IEnumerable and that I have to create IEqualityComparer for more advanced materials, but is there a way with which you can specify which duplicate element to return?

For example, do you have List<T>

List<MyClass> test = new List<MyClass>();
test.Add(new MyClass {ID = 1, InnerID = 4});
test.Add(new MyClass {ID = 2, InnerID = 4});
test.Add(new MyClass {ID = 3, InnerID = 14});
test.Add(new MyClass {ID = 4, InnerID = 14});

Then you do:

var distinctItems = test.Distinct(new DistinctItemComparer());

class DistinctItemComparer : IEqualityComparer<MyClass> {

    public bool Equals(MyClass x, MyClass y) {
        return x.InnerID  == y.InnerID;;
    }

    public int GetHashCode(MyClassobj) {
        return obj.InnerID.GetHasCode();
    }
}

This code will return classes with identifiers 1 and 3. Is there a way to return match identifiers 2 and 4.

+3
source share
5 answers

You do not want to distinguish then - you want to group your elements and select the "maximum" element for them based on ID:

    var distinctItems = test.Distinct(new DistinctItemComparer());

    var otherItems = test.GroupBy(a => a.InnerID, (innerID, values) => values.OrderBy(b => b.ID).Last());

    var l1 = distinctItems.ToList();
    var l2 = otherItems.ToList();

l1 = current list l2 = your desired list

+3
source

, , , , Distinct , .

, , . :

items.OrderByDescending(x => x.Id)
     .Distinct(new DistinctItemComparer());

: Distinct DistinctBy MoreLINQ:

items.OrderByDescending(x => x.Id)
     .DistinctBy(x => x.InnerId);

, LINQ to Objects Distinct , MoreLINQ:) ( , , .)

- GroupBy - .

+4

Distinct, Where. :

var ids = new[] { 2, 4 };
var newSeq = test.Where(m => ids.Contains(m.ID));
+2

, , group by:

 var q = from t in tests
         group t by t.InnerID into g
         select g.First(...);

select , , (, First(...)). Distinct , .

+2

, .

Distinct()used to search for individual items. If you are worried about which element to return ... then it is obvious that they are not truly identical (and therefore not distinguishable), and you have a flaw in your design.

+1
source

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


All Articles