我试图在列表中找到相似的相邻项并计算其编号,例如:

List<string> list = new List<string> {"a", "a", "b", "d", "c", "c"};

期望输出:
A=2,C=2
我所做的是使用for循环遍历列表中的每个元素,并查看它是否有相似的相邻元素,但可以理解,它给出了ArgumentOutOfRangeException(),因为我不知道如何跟踪迭代器的位置,以便它不会超出界限。以下是我所做的:
for (int j = 0; j < list.Count; j++)
{
      if (list[j] == "b")
      {
             if ((list[j + 1] == "b") && (list[j - 1] == "b"))
             {
                     adjacent_found = true;
             }
      }
}

尽管如此,如果在列表中找到类似的相邻元素有另一种更简单的方法,而不是使用for循环迭代,请给出建议。谢谢。

最佳答案

你可以这样做:

static IEnumerable<Tuple<string, int>> FindAdjacentItems(IEnumerable<string> list)
{
    string previous = null;
    int count = 0;
    foreach (string item in list)
    {
        if (previous == item)
        {
            count++;
        }
        else
        {
            if (count > 1)
            {
                yield return Tuple.Create(previous, count);
            }
            count = 1;
        }
        previous = item;
    }

    if (count > 1)
    {
        yield return Tuple.Create(previous, count);
    }
}

关于c# - 计算List <string>中的相似相邻项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28648409/

10-12 16:50