在 C# 列表中查找重复项索引的最优雅方法是什么 [英] What is the most elegant way to find index of duplicate items in C# List

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

问题描述

我有一个 List 包含重复项,我需要找到每个的索引.

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# 列表中查找重复项索引的最优雅方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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