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