問題描述
我有一個 List<string>
包含重復(fù)項,我需要找到每個項的索引.
I've got a List<string>
that contains duplicates and I need to find the indexes of each.
除了遍歷所有項目之外,最優(yōu)雅、最有效的方法是什么.我在 .NET 4.0 上,所以 LINQ 是一個選項.我已經(jīng)進行了大量的搜索和連接找到任何東西.
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.
樣本數(shù)據(jù):
var data = new List<string>{"fname", "lname", "home", "home", "company"}();
我需要獲取家"的索引.
I need to get the indexes of "home".
推薦答案
您可以從包含它的索引的每個項目創(chuàng)建一個對象,然后對值進行分組并過濾掉包含多個對象的組.現(xiàn)在您有了一個分組列表,其中包含包含文本及其原始索引的對象:
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);
這篇關(guān)于在 C# List 中查找重復(fù)項索引的最優(yōu)雅方法是什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!