Recently I have found it necessary to find the missing numbers in a number sequence. Investigating this I have solved it in the following way:
List<int> myLista = new List<int>() { 1, 2, 3, 5, 8, 9 };
int primero = myLista.OrderBy(x => x).First();
int ultimo = myLista.OrderBy(x => x).Last();
var resultado = Enumerable.Range(primero, ultimo - primero + 1).Except(list);
But now I also need to know exactly where the sequence of numbers is interrupted? , I was doing some research and found the following page dealing with this topic: Find Missing Values in a Sequence of Numbers and Other Sequence Related lists as IEnumerable Extensions Here's a method that does exactly what I want, it's called: SequenceReportMissingsBreakStarts
.
But all the methods are creating "queries" with significant side effects, this is why I decided to take the example shown in the comments suggested by another user. But I can't get this to work for me:
private IEnumerable SequenceFindMissings(IEnumerable sequence)
{
return sequence.Zip(sequence.Skip(1), (a, b) => Enumerable.Range(a + 1, (b - a) - 1))
.SelectMany(s => s);
}
private bool IsSequenceBroken(IEnumerable sequence)
{
return sequence.Zip(sequence.Skip(1), (a, b) => b - a)
.Any(v => v != 1);
}
private IEnumerable SequenceReportMissingsBreakStarts(IList sequence)
{
return sequence.Zip(sequence.Skip(1), (a, b) => new { b, a })
.Where(v => v.b - v.a > 1)
.Select(v => v.a);
}
I get the error: Ilist
, IEnumerable
does not contain a definition for Skip
and I have added the references:
using System.Linq;
using System.Collections;
using System.Collections.Generic;
Why can't I use "Skip" in these methods, how should I modify them to make it work? , or any suggestions without having to use queries?
Environment: Visual Studio 2017 & .NetFramework 4.5.2
In principle you must take into account that you are passing parameters to your methods through Interfaces (
IEnumerable
,IList
).The problem is that you must indicate the type of object that these "Generic Lists" will contain in order to later be able to use LinQ (
Skip()
).In your case they would be "generic lists" of type
int
(IEnumerable<int>
), the code would be like this: