Remove duplicates from list of object

后端 未结 5 1956
悲&欢浪女
悲&欢浪女 2021-01-20 11:52

I have MyObject with field: id, a, b, c, e, f and I have List with 500 000 items, now how can I remove all duplicate items with of the same value of the parameter a, c, f? <

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 12:17

    Well you can always use LINQ Distinct() like this :

    var matches = list.Distinct(new Comparer()).ToList();
    

    But for Ditsinct() to work you need to impletemnt Comparer for your Class:

    class Comparer : IEqualityComparer
    {
        public bool Equals(MyObject x, MyObject y)
        {
            return x.a == y.a && x.c == y.c && x.f == y.f;
        }
    
        public int GetHashCode(MyObject obj)
        {
            return (obj.a + obj.c + obj.f).GetHashCode();
        }
    }
    

提交回复
热议问题