Know when my list is coming with values in sequence

0

I have a List<int> :

  

[2,3,5,4,6]

Although they are not in order, it is a sequence of numbers (2,3,4,5,6) How do I validate this?

  

NOTE: There will always be 5 positions and the numbers will be from 1 to 6

    
asked by anonymous 26.05.2018 / 00:17

2 answers

1

You can use SequenceEqual next to < a href="https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx"> OrderBy . Assuming your list calls lista , see how it would look:

lista.SequenceEqual(lista.OrderBy(x => x))

This line will return a boolean saying whether it is sorted or not.

  

See working at DotNetFiddle .

    
26.05.2018 / 00:57
0

You can use the following function:

public bool hasNumberSequence(List<int> numbers)
{
    numbers.Sort();

    int numerosSequenciais = 0;

    for (int i = 1; i < numbers.Count(); i++)
    {
        if (numbers[i] != (numbers[i - 1] + 1))
            numerosSequenciais = 0;
        else
            numerosSequenciais++;
    }

    return numerosSequenciais >= 4;
}

This function returns true if there is a sequence of at least 4 numbers in the list of int and false if it does not exist.

Usage Examples

List<int> numeros = new List<int>() { 0, 3, 5, 4, 6 };
Console.WriteLine(hasNumberSequence().ToString(numeros)); // True

numeros = new List<int>() { 2, 3, 5, 4, 6 };
Console.WriteLine(hasNumberSequence(numeros).ToString()); // True

numeros = new List<int>() { 2, 1, 0, 4, 6 };
Console.WriteLine(hasNumberSequence(numeros).ToString()); // False
    
26.05.2018 / 00:57