本文翻译自:C# LINQ find duplicates in List

使用LINQ,如何从List<int>检索包含重复项不止一次及其值的列表?


#1楼

参考:https://stackoom.com/question/1fP0S/C-LINQ在列表中查找重复项


#2楼

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: 在LINQ中,这转换为:

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();

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. 这将返回一个匿名类型的List ,并且每个元素都将具有属性ElementCounter ,以检索所需的信息。

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. 这将返回一个字典,将您的元素作为键,并将其重复的次数作为值。


#3楼

You can do this: 你可以这样做:

var list = new[] {1,2,3,1,4,2};
var duplicateItems = list.Duplicates();

With these extension methods: 使用这些扩展方法:

public static class Extensions
{public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector){var grouped = source.GroupBy(selector);var moreThan1 = grouped.Where(i => i.IsMultiple());return moreThan1.SelectMany(i => i);}public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source){return source.Duplicates(i => i);}public static bool IsMultiple<T>(this IEnumerable<T> source){var enumerator = source.GetEnumerator();return enumerator.MoveNext() && enumerator.MoveNext();}
}

Using IsMultiple() in the Duplicates method is faster than Count() because this does not iterate the whole collection. 在Duplicates方法中使用IsMultiple()比Count()更快,因为这不会迭代整个集合。


#4楼

Another way is using HashSet : 另一种方法是使用HashSet

var hash = new HashSet<int>();
var duplicates = list.Where(i => !hash.Add(i));

If you want unique values in your duplicates list: 如果要在重复项列表中使用唯一值:

var myhash = new HashSet<int>();
var mylist = new List<int>(){1,1,2,2,3,3,3,4,4,4};
var duplicates = mylist.Where(item => !myhash.Add(item)).ToList().Distinct().ToList();

Here is the same solution as a generic extension method: 这是与通用扩展方法相同的解决方案:

public static class Extensions
{public static IEnumerable<TSource> GetDuplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IEqualityComparer<TKey> comparer){var hash = new HashSet<TKey>(comparer);return source.Where(item => !hash.Add(selector(item))).ToList();}public static IEnumerable<TSource> GetDuplicates<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer){return source.GetDuplicates(x => x, comparer);      }public static IEnumerable<TSource> GetDuplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector){return source.GetDuplicates(selector, null);}public static IEnumerable<TSource> GetDuplicates<TSource>(this IEnumerable<TSource> source){return source.GetDuplicates(x => x, null);}
}

#5楼

Find out if an enumerable contains any duplicate : 找出可枚举是否包含任何重复项 :

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

Find out if all values in an enumerable are unique : 找出可枚举中的所有值是否唯一

var allUnique = enumerable.GroupBy(x => x.Key).All(g => g.Count() == 1);

#6楼

I created a extention to response to this you could includ it in your projects, I think this return the most case when you search for duplicates in List or Linq. 我创建了一个扩展名以响应此问题,您可以将其包括在项目中,我认为当您在List或Linq中搜索重复项时,这种情况最常见。

Example: 例:

//Dummy class to compare in list
public class Person
{public int Id { get; set; }public string Name { get; set; }public string Surname { get; set; }public Person(int id, string name, string surname){this.Id = id;this.Name = name;this.Surname = surname;}
}//The extention static class
public static class Extention
{public static IEnumerable<T> getMoreThanOnceRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class{ //Return only the second and next reptitionreturn extList.GroupBy(groupProps).SelectMany(z => z.Skip(1)); //Skip the first occur and return all the others that repeats}public static IEnumerable<T> getAllRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class{//Get All the lines that has repeatingreturn extList.GroupBy(groupProps).Where(z => z.Count() > 1) //Filter only the distinct one.SelectMany(z => z);//All in where has to be retuned}
}//how to use it:
void DuplicateExample()
{//Populate ListList<Person> PersonsLst = new List<Person>(){new Person(1,"Ricardo","Figueiredo"), //fist Duplicate to the examplenew Person(2,"Ana","Figueiredo"),new Person(3,"Ricardo","Figueiredo"),//second Duplicate to the examplenew Person(4,"Margarida","Figueiredo"),new Person(5,"Ricardo","Figueiredo")//third Duplicate to the example};Console.WriteLine("All:");PersonsLst.ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));/* OUTPUT:All:1 -> Ricardo Figueiredo2 -> Ana Figueiredo3 -> Ricardo Figueiredo4 -> Margarida Figueiredo5 -> Ricardo Figueiredo*/Console.WriteLine("All lines with repeated data");PersonsLst.getAllRepeated(z => new { z.Name, z.Surname }).ToList().ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));/* OUTPUT:All lines with repeated data1 -> Ricardo Figueiredo3 -> Ricardo Figueiredo5 -> Ricardo Figueiredo*/Console.WriteLine("Only Repeated more than once");PersonsLst.getMoreThanOnceRepeated(z => new { z.Name, z.Surname }).ToList().ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));/* OUTPUT:Only Repeated more than once3 -> Ricardo Figueiredo5 -> Ricardo Figueiredo*/
}

C#LINQ在列表中查找重复项相关推荐

  1. python的元组是否能重复_python – 在带有元组的列表列表中查找重复项

    我试图找到嵌套在列表中的元组内的重复项.整个建筑也是一个清单.如果有其他更好的方法来组织这个让我的问题得到解决 – 我很高兴知道,因为这是我在路上建立的东西. pairsList = [ [1, (1 ...

  2. 如何在保留订单的同时从列表中删除重复项?

    是否有内置的程序在保留顺序的同时从Python列表中删除重复项? 我知道我可以使用集合来删除重复项,但这会破坏原始顺序. 我也知道我可以这样滚动自己: def uniq(input):output = ...

  3. 从Dart列表中删除重复项的2种方法

    本文向您展示了从 Flutter 中的列表中删除重复项的 2 种方法.第一个适用于原始数据类型列表.第二个稍微复杂一些,但适用于map****列表或对象列表. 转换为 Set 然后反转为 List 这 ...

  4. C语言从未排序的链接列表中删除重复项的算法(附完整源码)

    C语言从未排序的链接列表中删除重复项的算法 C语言从未排序的链接列表中删除重复项的算法完整源码(定义,实现,main函数测试) C语言从未排序的链接列表中删除重复项的算法完整源码(定义,实现,main ...

  5. 在 Excel 中如何使用宏示例删除列表中的重复项

    概要:在 Microsoft Excel 中,可以创建宏来删除列表中的重复项.也可以创建宏来比较两个列表,并删除第二个列表中那些也出现在第一个(主)列表中的项目.如果您想将两个列表合并在一起,或者如果 ...

  6. Python统计列表中的重复项出现的次数的方法

    本文实例展示了Python统计列表中的重复项出现的次数的方法,是一个很实用的功能,适合Python初学者学习借鉴.具体方法如下: 对一个列表,比如[1,2,2,2,2,3,3,3,4,4,4,4],现 ...

  7. scala 去除重复元素_Scala程序从列表中删除重复项

    scala 去除重复元素 List in Scala is a collection that stores data in the form of a liked-list. The list is ...

  8. python从后面删除重复项_如何从Python列表中删除重复项

    如何从Python列表中删除重复项 了解如何从Python中的List中删除重复项技巧. 实例 从列表中删除任何重复项: mylist = ["a", "b", ...

  9. python去掉字典重复项_从字典列表中删除重复项python

    我正在尝试从下面的列表中删除重复项distinct_cur = [{'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': ...

最新文章

  1. QuickBI助你成为分析师——数据源FAQ小结
  2. 干货 | 加速AI发展!一文了解GPU Computing
  3. List Control Utility
  4. 为什么wait和notify只能在synchronized中?
  5. sql int 转string_SQL智能代码补全引擎【sql-code-intelligence】介绍
  6. 经典基础算法之面试题(系列一)
  7. android 从assets和res中读取文件(转)
  8. Mr.J--C语言编译错误C3861
  9. 开源文本编辑器Vim的作者Bram Moolenaar推出了新的编程语言Zimbu.doc
  10. Java:接口文档示例
  11. excel内容合并脚本
  12. cryptoJs 前端用法
  13. PayPal个人账户不能提现了吗?怎么解决?
  14. 触动小精灵似乎已断开与互联网的连接解决方法
  15. Low-Light Image and Video Enhancement Using Deep Learning: A Survey 论文阅读笔记
  16. 好工具推荐-侧边翻译
  17. Qt 报错1:cannot find -lGL
  18. windows计算机搜索记录,win7清除文件搜索记录及电脑数据恢复教程
  19. Python——requests模块详解
  20. 京东云视频云全面支持AVS2标准

热门文章

  1. Python数据爬取之0基础小白实战(三)源码解析
  2. AutoJs学习-堆堆乐自动
  3. 魔塔之拯救白娘子~我的第一个VB6+DX8做的小游戏源码~13开始游戏-初始化
  4. 玉石效果?——UnityShader学习笔记
  5. JOB:前端面试10
  6. GOTURN 网络理解
  7. oracle数据库短期培训,Oracle数据库培训课件.ppt
  8. 吉林省白城市谷歌高清卫星地图下载
  9. 【Axure视频教程】商品价格区间筛选
  10. 给ubuntu server 16.04.6打preempt rt补丁