tags:

views:

5609

answers:

6

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 the repeated elements {2, 4}?

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

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

CVertex
This returns {0, 1, 2, 3, 4, 5} including repeated elements.
Ozgur Ozcitak
Oh, my mistake. I didn't notice you wanted to remove those duplicate entries.
CVertex
+10  A: 
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;
Bryan Watts
+2  A: 

If Linq isn't available to you because you have to support legacy code that can't be upgraded, then declare a Dictionary, where the first int is the number and the second int is the number of occurences. Loop through your List, loading up your Dictionary. When you're done, loop through your Dictionary selecting only those elements where the number of occurences is 1.

Corey Trager
+5  A: 

C# 2.0 solution:

 static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)
 {
  Dictionary<T, int> counts = new Dictionary<T, int>();
  foreach (T item in things)
  {
   int count;
   if (counts.TryGetValue(item, out count))
    counts[item] = ++count;
   else
    counts.Add(item, 1);
  }
  foreach (KeyValuePair<T, int> kvp in counts)
  {
   if (kvp.Value == 1)
    yield return kvp.Key;
  }
 }
Matt Howells
This will throw a KeyNotFoundException
Ch00k
This works but you need to change counts[item]++; intoif (counts.ContainsKey(item)) counts[item]++; else counts.Add(item, 1);
Ozgur Ozcitak
Fixed. Teach me to write code without seeing if it compiles!
Matt Howells
+2  A: 

I believe Matt meant to say:

 static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)
 {
     Dictionary<T, bool> uniques = new Dictionary<T, bool>();
     foreach (T item in things)
     {
         if (!(uniques.ContainsKey(item)))
         {
             uniques.Add(item, true);
         }
     }
     return uniques.Keys;
 }
Robert Rossney
This is the .NET 2.0 version of what CVertex posted. It also returns the duplicate elements.
Ozgur Ozcitak
If you could downvote your own posts I would.
Robert Rossney
Well, you can delete 'em.
Frederick
No, I prefer leaving them (as the French said the English occasionally shot an admiral) pour encourager l'autres.
Robert Rossney
+2  A: 

With lambda..

var all = new[] {0,1,1,2,3,4,4,4,5,6,7,8,8}.ToList();
var unique = all.GroupBy(i => i).Where(i => i.Count() == 1).Select(i=>i.Key);
Barbaros Alp