If you are trying to combine two lists
You can use Union .
List<int> results = lst1.Union(lst2).ToList();
You can also use Concat and Distinct to accomplish this:
List<int> lst3 = lst1.Concat(lst2).Distinct().ToList();
If you are trying to remove duplicates from the same list of objects
You can use Distinct with IEqualityComparer<> .
List<DataRow> results = lst1.Distinct(new RowComparer()).ToList(); public class RowComparer : IEqualityComparer<DataRow> { public bool Equals(DataRow x, DataRow y) { return x.Field<int>("ID") == y.Field<int>("ID"); } public int GetHashCode(DataRow obj) { return obj.Field<int>("ID").GetHashCode(); } }
If you are trying to combine multiple lists of objects and remove duplicates
You can use Union with IEqualityComparer<> .
List<DataRow> results = lst1.Union(lst2, new RowComparer()).ToList(); public class RowComparer : IEqualityComparer<DataRow> { public bool Equals(DataRow x, DataRow y) { return x.Field<int>("ID") == y.Field<int>("ID"); } public int GetHashCode(DataRow obj) { return obj.Field<int>("ID").GetHashCode(); } }
source share