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();
You need to re-assign the list again since LINQ does not change list in place:
mydIds = mydIds.Distinct().ToList();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With