Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Non-Distinct elements from an IEnumerable

Tags:

c#

linq

I have a class called Item. Item has an identifier property called ItemCode which is a string. I would like to get a list of all non-distinct Items in a list of Items.

Example:

List<Item> itemList = new List<Item>()
{
   new Item("code1", "description1"),
   new Item("code2", "description2"),
   new Item("code2", "description3"),
};

I want a list containing the bottom two entries

If I use

var distinctItems = itemsList.Distinct();

I get the list of distinct items which is great, but I want almost the opposite of that. I could subtract the the distinct list from the original list but that wouldn't contain ALL repeats, just one instance of each.

I've had a play and can't figure out an elegant solution. Any pointers or help would be much appreciated. Thanks!

I have 3.5 so LINQ is available

like image 803
RichK Avatar asked Jan 24 '10 14:01

RichK


2 Answers

My take:

var distinctItems = 
    from list in itemsList
    group list by list.ItemCode into grouped
    where grouped.Count() > 1
    select grouped;
like image 101
magnus Avatar answered Sep 22 '22 05:09

magnus


as an extension method:

public static IEnumerable<T> NonDistinct<T, TKey> (this IEnumerable<T> source, Func<T, TKey> keySelector)
{
   return source.GroupBy(keySelector).Where(g => g.Count() > 1).SelectMany(r => r);
}
like image 24
increddibelly Avatar answered Sep 20 '22 05:09

increddibelly