假设您有一个MyObject列表,如下所示:
public class MyObject
{
public int ObjectID {get;set;}
public string Prop1 {get;set;}
}
如何从列表中删除重复项,其中可能存在多个具有相同ObjectID的对象实例。
感谢。
答案 0 :(得分:45)
您可以使用GroupBy()
并选择每个组中的第一项来实现您的目标 - 假设您要为每个不同的ObjectId
属性选择一个项目:
var distinctList = myList.GroupBy(x => x.ObjectID)
.Select(g => g.First())
.ToList();
或者MoreLinq project中还有DistinctBy()
允许更简洁的语法(但会为项目添加依赖项):
var distinctList = myList.DistinctBy( x => x.ObjectID).ToList();
答案 1 :(得分:12)
您可以使用Distinct()
方法执行此操作。但由于该方法使用默认的相等比较器,因此您的类需要像这样实现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();
}
}
现在您可以使用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();
答案 2 :(得分:3)
您可以通过实现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();
}
}
然后简单地说:
myList.Distinct(new MyObjectComparer())