C # Get no duplicates in list

With this list:

int[] numbers = {1,2,2,3,3,4,4,5}; 

I can remove duplicates using the Distinct () function so that the list reads: 1,2,3,4,5

however, I want the opposite. I want him to remove all duplicate numbers, leaving me with unique ones.

Thus, the list will look like this: 1.5.

How to do it?

+6
source share
3 answers

One of the methods -

 var singles = numbers.GroupBy(n => n) .Where(g => g.Count() == 1) .Select(g => g.Key); // add .ToArray() etc as required 
+13
source

What is an extension worth checking for if a sequence contains more than N elements:

 public static bool CountMoreThan<TSource>(this IEnumerable<TSource> source, int num) { if (source == null) throw new ArgumentNullException("source"); if (num < 0) throw new ArgumentException("num must be greater or equal 0", "num"); ICollection<TSource> collection = source as ICollection<TSource>; if (collection != null) { return collection.Count > num; } ICollection collection2 = source as ICollection; if (collection2 != null) { return collection2.Count > num; } int count = 0; using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (++count <= num + 1) if (!enumerator.MoveNext()) return false; } return true; } 

Now it is easy and effective:

 var allUniques = numbers.GroupBy(i => i) .Where(group => !group.CountMoreThan(1)) .Select(group => group.Key).ToList(); 

Demo

Or, as @KingKing on Jon commented on the answer:

 var allUniques = numbers.GroupBy(i => i) .Where(group => !group.Skip(1).Any()) .Select(group => group.Key).ToList(); 
+9
source
 var cleanArray = numbers.GroupBy(x=>x) .Where(x=>x.Count() == 1) .SelectMany(x=>x) .ToArray(); 
+5
source

Source: https://habr.com/ru/post/954237/


All Articles