Using LINQ, from a List
, how can I retrieve a list that contains entries repeated more than once and their values?
You can do this:
var list = new[] {1,2,3,1,4,2};
var duplicateItems = list.Duplicates();
With these extension methods:
public static class Extensions
{
public static IEnumerable Duplicates(this IEnumerable source, Func selector)
{
var grouped = source.GroupBy(selector);
var moreThan1 = grouped.Where(i => i.IsMultiple());
return moreThan1.SelectMany(i => i);
}
public static IEnumerable Duplicates(this IEnumerable source)
{
return source.Duplicates(i => i);
}
public static bool IsMultiple(this IEnumerable source)
{
var enumerator = source.GetEnumerator();
return enumerator.MoveNext() && enumerator.MoveNext();
}
}
Using IsMultiple() in the Duplicates method is faster than Count() because this does not iterate the whole collection.