4

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();
5
  • have you tried mydIds = mydIds.OrderBy(x => x).Distinct().ToList() ? Commented Jun 1, 2013 at 14:54
  • Do you have a more complete code sample? I have no problem removing duplicate long values from a collection via LINQ's Distinct call; no OrderBy necessary. Commented Jun 1, 2013 at 14:56
  • 2
    You need to reassing the result of Distinct to a list Commented Jun 1, 2013 at 14:56
  • @Steve I think that must be it. Codingjoe, you need to re-assign the result. It does not change the existing list; it creates a new list. Commented Jun 1, 2013 at 14:56
  • I see that my English is not that sharp, got my post edited in lightweight, but in a more understandable format :) Commented Jun 1, 2013 at 18:07

3 Answers 3

7

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

 mydIds = mydIds.Distinct().ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh I feel so stupid. I actually had it working with myIds.Distict().ToList(); I had my breakpoint on a wrong collection variable. :/
3

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.

Comments

1

You don't reassing the result of the Distinct to a List object

List<long> id = new List<long>() {20,50,34, 20, 21, 45, 50, 900, 34, 20};
id = id.Distinct().ToList();
id.ForEach(x => Console.WriteLine(x));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.