使用LINQ,从列表< int> 中,如何检索包含多次重复的条目的列表及其值?
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();这将返回一个匿名类型的列表,每个元素将具有属性Element和Counter,检索您需要的信息。
This will return a List of an anonymous type, and each element will have the properties Element and Counter, to retrieve the informations 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在列表中找到重复的
发布评论