在C#列表中查找重复字符串的索引 [英] Find indexes of duplicate strings in C# List

查看:46
本文介绍了在C#列表中查找重复字符串的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表:

["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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆