Count similar adjacent items in List<string>

adjacency-list, c#, count, list

Solution

You can do something like this:

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

Problem

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 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.

Original source