removing duplicates in a list with linq

后端 未结 3 2095
日久生厌
日久生厌 2020-12-15 05:22

Suppose you have a list of MyObject like this:

public class MyObject
{
  public int ObjectID {get;set;}
  public string Prop1 {get;set;}
}

3条回答
  •  萌比男神i
    2020-12-15 05:22

    You can do this using the Distinct() method. But since that method uses the default equality comparer, your class needs to implement IEquatable like this:

    public class MyObject : IEquatable
    {
        public int ObjectID {get;set;}
        public string Prop1 {get;set;}
    
        public bool Equals(MyObject other)
        {
            if (other == null) return false;
            else return this.ObjectID.Equals(other.ObjectID); 
        }
    
        public override int GetHashCode()
        {
            return this.ObjectID.GetHashCode();
        }
    }
    

    Now you can use the Distinct() method:

    List myList = new List();
    myList.Add(new MyObject { ObjectID = 1, Prop1 = "Something" });
    myList.Add(new MyObject { ObjectID = 2, Prop1 = "Another thing" });
    myList.Add(new MyObject { ObjectID = 3, Prop1 = "Yet another thing" });
    myList.Add(new MyObject { ObjectID = 1, Prop1 = "Something" });
    
    var duplicatesRemoved = myList.Distinct().ToList();
    

提交回复
热议问题