How to get a distinct list from a List of objects?

后端 未结 10 1188
滥情空心
滥情空心 2020-12-24 04:59

I have a List someList.

class MyClass
{
    public int Prop1...
    public int Prop2...
    public int Prop3...
}
相关标签:
10条回答
  • 2020-12-24 05:20

    Just use the build-in function DistinctBy of Microsoft Ajax Ultility library like the sample blow:

    First including library

    using Microsoft.Ajax.Utilities;
    

    then

    var distinctList = yourList.DistinctBy(x => x.Prop2).ToList();
    
    0 讨论(0)
  • 2020-12-24 05:22

    If you would like to Distinct your list by multiple fields, You have to create an instance of IEqualityComparer interface:

    public class MyComparer : IEqualityComparer<MyModel>
    {
        public bool Equals(MyModel x, MyModel y)
        {
           // compare multiple fields
            return
                x.Field1 == y.Field1 &&
                x.Field2 == y.Field2 &&
                x.Field3 == y.Field3 ;
        }
    
        public int GetHashCode(MyModel obj)
        {
            return 
                obj.Field1.GetHashCode() + 
                obj.Field2.GetHashCode() + 
                obj.Field3.GetHashCode();
        }
    }
    

    Then use the comparer to distinct your list:

    var distinctedList = myList.Distinct(new MyComparer()).ToList();
    
    0 讨论(0)
  • 2020-12-24 05:33

    Override Equals(object obj) and GetHashCode() methods:

    class MyClass
    {
        public int Prop1 { get; set; }
        public int Prop2 { get; set; }
        public int Prop3 { get; set; }
    
        public override bool Equals(object obj)
        {
            return ((MyClass)obj).Prop2 == Prop2;
        }
        public override int GetHashCode()
        {
            return Prop2.GetHashCode();
        }
    }
    

    and then just call:

    List<MyClass> distinctList = someList.Distinct().ToList();
    
    0 讨论(0)
  • 2020-12-24 05:34

    Since the introduction of value tuples, if you want a LINQ equivalent to SQL's DISTINCT

    items.GroupBy(item => (item.prop1, item.prop2, ...)).Select(group => group.First())
    
    0 讨论(0)
提交回复
热议问题