How to clear items in list <> that are similar to each other in C #

I have a list, but there are many elements in this list that have the same value. I want to clear values โ€‹โ€‹that have the same value and have one from each group of elements.

+4
source share
5 answers

If you are using 3.5+, you can use Linq to accomplish this:

 myDistinctList = myList.Distinct(); 

This assumes the list value is primitive or an object that implements IComparable.

+7
source

you can put them in a set that provides uniqueness if you have #equals for proper comparison.

+1
source

In C # 4.0, use the Distinct extension method:

 var values=new List<Type>; var result=result.Distict().ToList(); return result; 

Update: if your type is used for a reference type:

 result.Distict(IEqualityComparer<Type>) 
0
source

You can use linq :

  • Delete duplicate: .Distinct ()
  • Group: .GroupBy ()
0
source

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(); } } 
0
source

Source: https://habr.com/ru/post/1381131/


All Articles