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}
?
From stackoverflow
-
var nums = new int{ 0...4,4,5}; var distinct = nums.Distinct();
make sure you're using Linq and .NET framework 3.5.
Ozgur Ozcitak : This returns {0, 1, 2, 3, 4, 5} including repeated elements.CVertex : Oh, my mistake. I didn't notice you wanted to remove those duplicate entries. -
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;
-
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.
-
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; } }
Ch00k : This will throw a KeyNotFoundExceptionOzgur Ozcitak : This works but you need to change counts[item]++; into if (counts.ContainsKey(item)) counts[item]++; else counts.Add(item, 1);Matt Howells : Fixed. Teach me to write code without seeing if it compiles! -
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; }
Ozgur Ozcitak : This is the .NET 2.0 version of what CVertex posted. It also returns the duplicate elements.Robert Rossney : If you could downvote your own posts I would.Frederick : Well, you can delete 'em.Robert Rossney : No, I prefer leaving them (as the French said the English occasionally shot an admiral) pour encourager l'autres. -
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);
0 comments:
Post a Comment