0

I have a List of Data, and I want to find the length of the longest sequence of elements in the list that are equal. This is easy to do with a loop over the collection, however I was wondering if there is a Linq query that can do this. Thanks for your help.

user200814
  • 275
  • 1
  • 3
  • 8

2 Answers2

1
var longest = list.Select((x,i) => list.Skip(i).TakeWhile(c => c == x).Count()).Max();
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
0

Just iterate through the sequence incrementing a counter when an item is equal to the previous and resetting it if it's not.

public static int LongestSequence<T>(IEnumerable<T> source, IEqualityComparer<T> comparer)
{
    comparer = comparer ?? EqualityComparer<T>.Default;

    using (var iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext()) //empty sequence
            return 0;
        T previous = iterator.Current;
        int count = 1;
        int maxCount = 1;

        while (iterator.MoveNext())
        {
            if (comparer.Equals(iterator.Current, previous))
            {
                count++;
            }
            else
            {
                maxCount = Math.Max(maxCount, count);
                count = 1;
                previous = iterator.Current;
            }
        }

        return maxCount;
    }
}
Servy
  • 202,030
  • 26
  • 332
  • 449