Ozgur Ozcitak Ozgur Ozcitak - 1 month ago 13
C# Question

Selecting Unique Elements From a List in C#

How do I select the unique elements from the list

{0, 1, 2, 2, 2, 3, 4, 4, 5}
so that I get
{0, 1, 3, 5}
, effectively removing all instances of the repeated elements
{2, 4}
?

Answer
var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };

var uniqueNumbers =
    from n in numbers
    group n by n into nGroup
    where nGroup.Count() == 1
    select nGroup.Key;

// { 0, 1, 3, 5 }