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}
?
views:
5609answers:
6
+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
2008-11-15 08:23:03
This returns {0, 1, 2, 3, 4, 5} including repeated elements.
Ozgur Ozcitak
2008-11-15 08:24:36
Oh, my mistake. I didn't notice you wanted to remove those duplicate entries.
CVertex
2008-11-15 08:26:48
+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
2008-11-15 08:35:41
+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
2008-11-15 09:32:44
+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
2008-11-15 14:45:39
This works but you need to change counts[item]++; intoif (counts.ContainsKey(item)) counts[item]++; else counts.Add(item, 1);
Ozgur Ozcitak
2008-12-23 09:27:39
+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
2008-11-15 17:58:08
This is the .NET 2.0 version of what CVertex posted. It also returns the duplicate elements.
Ozgur Ozcitak
2008-12-23 09:26:06
No, I prefer leaving them (as the French said the English occasionally shot an admiral) pour encourager l'autres.
Robert Rossney
2009-01-19 10:19:30
+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
2009-01-16 12:49:35