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}
?
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 }
var nums = new int{ 0...4,4,5};
var distinct = nums.Distinct();
make sure you're using Linq and .NET framework 3.5.