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.

  • Mandatory by standard means Linq? - Andrei NOP

3 answers 3

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?

  • and it is possible an example with where? - Mike Waters
  • 2
    No, because it is better not to do so - Andrey NOP
  • I have something like j.Items.Where (k => k.Value == 1) .Count () and I need to remove the same k.Value from Items - Mike Waters
  • Items - IOrderedEnumerable - Mike Waters
  • 2
    What mistake? Did you write like me literally? This is an extension method, it must be in a separate class, this must be specified, etc. - Andrei NOP

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.

  • If the array (or any other IList) is still fine, but the author did not say that he has an array - Andrew NOP
  • Well, if in this context, then you are right. - iluxa1810

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