C# LINQ find duplicates in List

前端 未结 9 1215
星月不相逢
星月不相逢 2020-11-22 07:57

Using LINQ, from a List, how can I retrieve a list that contains entries repeated more than once and their values?

9条回答
  •  忘了有多久
    2020-11-22 08:46

    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.

提交回复
热议问题