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.
Asked
Active
Viewed 114 times
0
-
8Paste the code with the loop, we have no idea what your data is like.. – Lews Therin Feb 01 '13 at 21:45
-
1It shouldn't matter, all that matters is that the element type supports equality comparison. Pretend it's a List of integers. – user200814 Feb 01 '13 at 21:48
2 Answers
1
var longest = list.Select((x,i) => list.Skip(i).TakeWhile(c => c == x).Count()).Max();

Eren Ersönmez
- 38,383
- 7
- 71
- 92
-
1Note that you do a lot of counting over and over again needlessly...This is O(n^2) when it could be O(n). If that matter to the OP... – Servy Feb 01 '13 at 21:51
-
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