Reputation:
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
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
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
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
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
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
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
Reputation: 8201
Use HashSet<T>
if you are on .NET 3.5, or Iesi.Collections (NHibernate uses this)
Upvotes: 1