我有一个字符串列表:
["String1"]
["String2"]
["String1"]
["String3"]
["String2"]
["String1"]
我需要在列表中搜索并找到“String1”的索引,并计算“String1”出现的次数。我已经查看了这个答案,但我是 C# 中这种类型的编码的新手,我不清楚如何提取索引值,所以如果你能解释如何使用这个解决方案,那就太好了!
来自另一个答案的代码,我将在此处复制以供参考,
var duplicates = data
.Select((t,i) => new { Index = i, Text = t })
.GroupBy(g => g.Text)
.Where(g => g.Count() > 1);
返回一个IEnumerable
of IGrouping
,它本身就是IEnumerable
一个匿名类型。您可以像这样从结果中获取索引:
foreach(var group in duplicates)
{
Console.WriteLine("Duplicates of {0}:", group.Key)
foreach(var x in group)
{
Console.WriteLine("- Index {0}:", x.Index)
}
}
但是,如果您只想获取索引列表,则可以使用SelectMany
扩展方法:
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);
这将返回一个IEnumerable
of int
。
从了解答案中的代码开始(请参阅下面的评论):
// Produce an enumeration of Index/Text pairs
var duplicates = data
// First, add the index to the value by using Select with an anonymous type
.Select((t,i) => new { Index = i, Text = t })
// Next, group the results by the content of the string
.GroupBy(g => g.Text)
// Finally, keep only groups with more than one item.
.Where(g => g.Count() > 1);
让我们修改它以适应我们的目的:
// Produce an enumeration of Indexes of "String1"
var allString1Indexes = data
// First, add the index to the value by using Select with an anonymous type
.Select((t,i) => new { Index = i, Text = t })
// Keep only the "String1" items
.Where(p => p.Text == "String1")
// Use only indexes
.Select(p => p.Index);
您现在可以迭代结果,并打印 的所有索引"String1"
:
foreach (var i in allString1Indexes) {
Console.WriteLine("String1 is found at index {0}", i);
}
您可以使用ToDictionary
方法获取Dictionary<string, List<int>>
:
var duplicated = data.Select((x, i) => new { i, x })
.GroupBy(x => x.x)
.Where(g => g.Count() > 1)
.ToDictionary(g => g.Key, g => g.Select(x => x.i).ToList());
在每Key
一个索引列表中,字符串实际出现在源列表中。