user356178
user356178

Reputation:

How to determine duplicates in a collection of ints?

Let's say I've got the following values in a collection of integers:

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

The result I'd expect is {5,7}.

How can I do that? Maybe using LINQ?

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

Upvotes: 6

Views: 288

Answers (7)

ingo
ingo

Reputation: 5569

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();    

Upvotes: 2

jason
jason

Reputation: 241701

You can do this with built-in functionality with LINQ, and it works on LINQ providers like LINQ to SQL and EF and NHibernate:

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

Upvotes: 7

p.campbell
p.campbell

Reputation: 100607

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 Finding Duplicates Using LINQ

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160942

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();

Upvotes: 2

The Evil Greebo
The Evil Greebo

Reputation: 7138

Linq with group by having count will show you how to do a LINQ group by having count > 1

In your specific instance:

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

Upvotes: 1

user7116
user7116

Reputation: 64098

How 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;
    }
}

Upvotes: 5

Denis Biondic
Denis Biondic

Reputation: 8201

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

Upvotes: 1

Related Questions