算上名单,LT类似的相邻项目;串> [英] Count similar adjacent items in List<string>

查看:181
本文介绍了算上名单,LT类似的相邻项目;串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到类似的相邻项的列表和计算的数字,例如:

I'm trying to find similar adjacent items in List and count its number, e.g.:

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



所需的输出:

Desired Output:

A = 2,C = 2

a = 2, c = 2

我所做的就是利用for循环遍历的每个元素列表,看它是否也有类似的相邻元素,但可以理解它给 ArgumentOutOfRangeException(),因为我不知道如何保持迭代器的位置跟踪,以便它不走出界。下面是我做了什么:

What I've done is use for loop to iterate over each element of the list and to see whether it has similar adjacent element, but understandably it gives ArgumentOutOfRangeException() because I don't know how to keep track of the position of the iterator so that it doesn't go out of bounds. Here's what I've done:

for (int j = 0; j < list.Count; j++)
{
      if (list[j] == "b")
      {
             if ((list[j + 1] == "b") && (list[j - 1] == "b"))
             {
                     adjacent_found = true;
             }
      }
}



话说回来,如果有另一种更简单的方法来查找不是使用循环迭代其他列表类似的相邻的元素,请告知。谢谢

Having said that, if there's another easier way to find similar adjacent elements in a List other than using for loop iteration, please advise. Thanks.

推荐答案

您可以做这样的事情:

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);
    }
}

这篇关于算上名单,LT类似的相邻项目;串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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