I have a List of objects in C#. All of the objects contain a property ID. There are several objects that have the same ID property.
How can I trim the List (or make a
var list = GetListFromSomeWhere();
var list2 = GetListFromSomeWhere();
list.AddRange(list2);
....
...
var distinctedList = list.DistinctBy(x => x.ID).ToList();
More LINQ
at GitHub
Or if you don't want to use external dlls for some reason, You can use this Distinct
overload:
public static IEnumerable Distinct(
this IEnumerable source, IEqualityComparer comparer)
Usage:
public class FooComparer : IEqualityComparer
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Foo x, Foo y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.ID == y.ID
}
}
list.Distinct(new FooComparer());