What is the most elegant way to find index of duplicate items in C# List(在 C# List 中查找重复项索引的最优雅方法是什么)
问题描述
我有一个 List<string> 包含重复项,我需要找到每个项的索引.
I've got a List<string> that contains duplicates and I need to find the indexes of each.
除了遍历所有项目之外,最优雅、最有效的方法是什么.我在 .NET 4.0 上,所以 LINQ 是一个选项.我已经进行了大量的搜索和连接找到任何东西.
What is the most elegant, efficient way other than looping through all the items. I'm on .NET 4.0 so LINQ is an option. I've done tons of searching and connect find anything.
样本数据:
var data = new List<string>{"fname", "lname", "home", "home", "company"}();
我需要获取家"的索引.
I need to get the indexes of "home".
推荐答案
您可以从包含它的索引的每个项目创建一个对象,然后对值进行分组并过滤掉包含多个对象的组.现在您有了一个分组列表,其中包含包含文本及其原始索引的对象:
You can create an object from each item containing it's index, then group on the value and filter out the groups containing more than one object. Now you have a grouping list with objects containing the text and their original index:
var duplicates = data
.Select((t,i) => new { Index = i, Text = t })
.GroupBy(g => g.Text)
.Where(g => g.Count() > 1);
这篇关于在 C# List 中查找重复项索引的最优雅方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# List 中查找重复项索引的最优雅方法是什么
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
