removing duplicates in a list with linq

后端 未结 3 2079
日久生厌
日久生厌 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条回答
  • 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<MyObject> like this:

    public class MyObject : IEquatable<MyObject>
    {
        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<MyObject> myList = new List<MyObject>();
    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();
    
    0 讨论(0)
  • 2020-12-15 05:27

    You could create a custom object comparer by implementing the IEqualityComparer interface:

    public class MyObject
    {
        public int Number { get; set; }
    }
    
    public class MyObjectComparer : IEqualityComparer<MyObject>
    {
        public bool Equals(MyObject x, MyObject y)
        {
            return x.Id == y.Id;
        }
    
        public int GetHashCode(MyObject obj)
        {
            return obj.Id.GetHashCode();
        }
    }
    

    Then simply:

    myList.Distinct(new MyObjectComparer()) 
    
    0 讨论(0)
  • 2020-12-15 05:48

    You can use GroupBy() and select the first item of each group to achieve what you want - assuming you want to pick one item for each distinct ObjectId property:

    var distinctList = myList.GroupBy(x => x.ObjectID)
                             .Select(g => g.First())
                             .ToList();
    

    Alternatively there is also DistinctBy() in the MoreLinq project that would allow for a more concise syntax (but would add a dependency to your project):

    var distinctList = myList.DistinctBy( x => x.ObjectID).ToList();
    
    0 讨论(0)
提交回复
热议问题