Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate values in collection

I have a collection of longs List<long> myIds. I am populating the collection with id's. However I get some duplicates in the collection which I want to remove.

I have tried using distinct() on the collection but to no effect. Reordering and applying distinct() again did not help either.

What is the best way to remove these duplicates without writing custom logic?

I tried this:

mydIds.OrderBy(x => x).Distinct().ToList();
like image 545
codingjoe Avatar asked Dec 21 '22 04:12

codingjoe


2 Answers

You need to re-assign the list again since LINQ does not change list in place:

 mydIds = mydIds.Distinct().ToList();
like image 199
cuongle Avatar answered Jan 02 '23 07:01

cuongle


Alternatively if you are using 3.5 and above:

var hs = new HashSet<int>(myIds);

The hashset will be populated by the list. If the list contains duplicate entries they will be ignored. No exception will be thrown.

like image 36
Tom Fobear Avatar answered Jan 02 '23 06:01

Tom Fobear