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