Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Unique Elements From a List in C#

Tags:

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}?

like image 350
Ozgur Ozcitak Avatar asked Nov 15 '08 08:11

Ozgur Ozcitak


2 Answers

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 } 
like image 178
Bryan Watts Avatar answered Sep 22 '22 17:09

Bryan Watts


var nums = new int{ 0...4,4,5}; var distinct = nums.Distinct(); 

make sure you're using Linq and .NET framework 3.5.

like image 21
CVertex Avatar answered Sep 19 '22 17:09

CVertex