C# LINQ 在列表中查找重复项 [英] C# LINQ find duplicates in List

查看:76
本文介绍了C# LINQ 在列表中查找重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 LINQ,如何从 List 中检索包含重复多次的条目及其值的列表?

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

推荐答案

解决问题最简单的方法是根据元素的值对元素进行分组,如果元素多于一个,则选择一个代表该组的群组.在 LINQ 中,这转化为:

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to:

var query = lst.GroupBy(x => x)
              .Where(g => g.Count() > 1)
              .Select(y => y.Key)
              .ToList();

如果想知道元素重复了多少次,可以使用:

If you want to know how many times the elements are repeated, you can use:

var query = lst.GroupBy(x => x)
              .Where(g => g.Count() > 1)
              .Select(y => new { Element = y.Key, Counter = y.Count() })
              .ToList();

这将返回一个匿名类型的List,并且每个元素将具有属性ElementCounter,以检索您需要.

This will return a List of an anonymous type, and each element will have the properties Element and Counter, to retrieve the information you need.

最后,如果是你要找的字典,你可以使用

And lastly, if it's a dictionary you are looking for, you can use

var query = lst.GroupBy(x => x)
              .Where(g => g.Count() > 1)
              .ToDictionary(x => x.Key, y => y.Count());

这将返回一个字典,以您的元素作为键,并将其重复的次数作为值.

This will return a dictionary, with your element as key, and the number of times it's repeated as value.

这篇关于C# LINQ 在列表中查找重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆