简体   繁体   English

使用linq删除列表中的重复项

[英]removing duplicates in a list with linq

Suppose you have a list of MyObject like this: 假设您有一个MyObject列表,如下所示:

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

How do you remove duplicates from a list where there could be multiple instance of objects with the same ObjectID. 如何从列表中删除重复项,其中可能存在具有相同ObjectID的多个对象实例。

Thanks. 谢谢。

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: 您可以使用GroupBy()并选择每个组的第一项来实现您想要的 - 假设您要为每个不同的ObjectId属性选择一个项目:

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): 或者, MoreLinq项目中还有DistinctBy() ,它允许更简洁的语法(但会为项目添加依赖项):

var distinctList = myList.DistinctBy( x => x.ObjectID).ToList();

You can do this using the Distinct() method. 您可以使用Distinct()方法执行此操作。 But since that method uses the default equality comparer, your class needs to implement IEquatable<MyObject> like this: 但由于该方法使用默认的相等比较器,因此您的类需要像这样实现IEquatable<MyObject>

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: 现在您可以使用Distinct()方法:

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();

You could create a custom object comparer by implementing the IEqualityComparer interface: 您可以通过实现IEqualityComparer接口来创建自定义对象比较器:

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()) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM