For example:
1,2,3,4,5 - 5 elements
1,1,2,3,4,5 - 5 elements
1, 2, 1, 3, 4, 5 - 6 elements
Ie if next, then count as one, but if the same in different places, then no.
I would write like this:
static class Extensions { public static IEnumerable<T> SkipRepeating<T>(this IEnumerable<T> source) { bool first = true; T prev = default; foreach (T item in source) if (first || !EqualityComparer<T>.Default.Equals(prev, item)) { yield return item; first = false; prev = item; } } } and then:
int[] array = { 1, 2, 1, 3, 4, 5 }; Console.WriteLine(array.SkipRepeating().Count()); You can, of course, do the same thing using Where , but why?
Here is the solution through a simple Where :
int[] array = { 1, 1, 1, 3, 4, 5 }; var result=array.Where((a,i) =>i-1>=0?a!=array[i-1]:true).Count(); True, I did not understand why @AndreyNOP does not recommend doing so ... We are addressing by the index => there are no costs.
One possible simple and universal solution is to use the Aggregate() method. Example:
int[] array = { 1, 1, 1, 1, 3, 4, 5, 5, 1, 2 }; int? prev = null; var res = array.Aggregate(0, (total, next) => { if (next == prev) return total; prev = next; return total + 1; }); Console.WriteLine(res); // 6 Source: https://ru.stackoverflow.com/questions/926087/
All Articles