How to define duplicates in ints collection?

Let's say I have the following values ​​in a set of integers:

{1,3,4,5,5,6,7,7} 

The result that I expect will be {5,7} .

How can i do this? Perhaps using LINQ?

EDIT: The input collection is not sorted, so the algorithm should not rely on consecutive duplicates. Also, it doesn't matter if the resulting duplicate collection is sorted or not.

+6
source share
7 answers

You can do this with built-in functions with LINQ, and it works with LINQ providers such as LINQ to SQL and EF and NHibernate:

 var dups = collection.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key); 
+8
source

What about:

 public static IEnumerable<T> OnlyDupes<T>(this IEnumerable<T> source) { var seen = new HashSet<T>(); foreach (var item in source) { // HashSet<T>.Add returns: true if the element is added to the // HashSet<T> object; false if the element is already present. if (!seen.Add(item)) yield return item; } } 
+6
source
 var list = new List<int>() { 1, 3, 4, 5, 5, 6, 7, 7 }; var duplicates = list.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList(); 
+3
source

Try something like this:

 int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 }; var duplicates = listOfItems .GroupBy(i => i) .Where(g => g.Count() > 1) .Select(g => g.Key); foreach (var d in duplicates) Console.WriteLine(d); 

from Find duplicates using LINQ

+3
source
 var list = new List<int>(){1,3,4,5,5,6,7,7}; var query = ( from i in list group i by i into g where g.Count() > 1 select g.Key).ToList(); 
+3
source

Linq with a counted group will show you how to make a LINQ group with count> 1

In your particular case:

 var x = from i in new int[] { 1, 2, 2, 3 } group i by i into grp where grp.Count() > 1 select grp.Key; 
+2
source

Use HashSet<T> if you are on .NET 3.5, or Iesi.Collections (NHibernate uses this)

+1
source

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


All Articles