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

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

问题描述

使用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在列表中找到重复的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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