C#LINQ在列表中找到重复的

编程入门 行业动态 更新时间:2024-10-28 04:20:08
本文介绍了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在列表中找到重复的

本文发布于:2023-11-03 07:35:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表中   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!