什么是找到在C#列表重复项指数最优雅的方式 [英] What is the most elegant way to find index of duplicate items in C# List

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

问题描述

我有一个列表<字符串方式> 包含重复,我需要找到每个指标

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天全站免登陆