C# LINQ find duplicates in List

前端 未结 9 1216
星月不相逢
星月不相逢 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:42

    To find the duplicate values only :

    var duplicates = list.GroupBy(x => x.Key).Any(g => g.Count() > 1);
    

    Eg. var list = new[] {1,2,3,1,4,2};

    so group by will group the numbers by their keys and will maintain the count(number of times it repeated) with it. After that, we are just checking the values who have repeated more than once.

    To find the uniuqe values only :

    var unique = list.GroupBy(x => x.Key).All(g => g.Count() == 1);
    

    Eg. var list = new[] {1,2,3,1,4,2};

    so group by will group the numbers by their keys and will maintain the count(number of times it repeated) with it. After that, we are just checking the values who have repeated only once means are unique.

提交回复
热议问题