在C#列表中查找重复字符串的索引 [英] Find indexes of duplicate strings in C# List
问题描述
我有一个字符串列表:
["String1"]
["String2"]
["String1"]
["String3"]
["String2"]
["String1"]
我需要搜索和找到列表中"String1"的索引,并计算"String1"发生了多少次.我已经审查了
That I need to search and find the indexes of "String1" in the List and also count how many times "String1" occurred. I've reviewed this answer but I'm new to this type of coding in C# and I'm unclear how to extract the index values, so if you could explain how to use the solution, that'd be great!
推荐答案
另一个答案中的代码,我将在此处重复以供参考,
The code from the other answer, which I will duplicate here for reference,
var duplicates = data
.Select((t,i) => new { Index = i, Text = t })
.GroupBy(g => g.Text)
.Where(g => g.Count() > 1);
返回 IGrouping <的
,它本身是匿名类型的 IEnumerable
/code> IEnumerable
.您可以像这样从结果中获取索引:
Returns an IEnumerable
of IGrouping
, which is itself an IEnumerable
of an anonymous type. You can get the indexes out of the result like this:
foreach(var group in duplicates)
{
Console.WriteLine("Duplicates of {0}:", group.Key)
foreach(var x in group)
{
Console.WriteLine("- Index {0}:", x.Index)
}
}
However, if all you want to do is get a list of indexes, you can use the SelectMany
extension method:
var duplicateIndexes = data
.Select((t,i) => new { Index = i, Text = t })
.GroupBy(g => g.Text)
.Where(g => g.Count() > 1)
.SelectMany(g => g, (g, x) => x.Index);
这将返回 int
的 IEnumerable
.
这篇关于在C#列表中查找重复字符串的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!