Taher
Taher

Reputation: 593

LINQ: Return non-duplicate Items in a List

If I have a list like this:

List<int> test = new List<int>{1, 1, 2, 2, 3, 3, 4, 4, 5, 6 , 7 , 7 , 7};

Then using the .Distinct() method:

var distinctTest = test.Distinct();

Will make the result list like this: { 1, 2, 3, 4, 5, 6, 7 }

How can I make a distinct item list like this: { 5, 6 }

Upvotes: 3

Views: 6750

Answers (2)

Izekid
Izekid

Reputation: 185

test.Select(x => x).Distinct();

This will return a sequence (IEnumerable) of your values -- one per unique value.

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460118

So you want to remove all items which are duplicates?

You can use GroupBy:

var distinctTest = test
    .GroupBy(i => i)
    .Where(g => g.Count() == 1)
    .Select(g => g.Key);

Upvotes: 13

Related Questions