Finding consecutive numbers in c#

Solution 1:

This is the most efficient way to do it:

using System;

namespace ConsoleApp7
{
    public class Program
    {
        public static void Main(string[] args)
        {
        Console.WriteLine("Enter numbers separate by hypen : ");
        var name = Console.ReadLine();
        var numarray = name.Split('-');
        int firstValue = Convert.ToInt32(numarray[0]);

        bool cons = true;
        for (var i = 0;i<numarray.Length;i++ )
        {
            if (Convert.ToInt32(numarray[i])-i != firstValue)
            {
                cons = false;                   
                break;
            }
        }
        if (cons)
        {
            Console.WriteLine("Consecutive");
        }
        else
        {
            Console.WriteLine("Not Consecutive");
        }
    }
}

}

https://dotnetfiddle.net/P8VGjG

Solution 2:

You can simplify like this,

 static void Main(string[] args)
    {
        Console.WriteLine("Enter numbers separate by hypen : ");
        var name = Console.ReadLine();
        int[] numarray = Array.ConvertAll(name.Split('-'), int.Parse); 
        if (IsSequential(numarray))
        {
            Console.WriteLine("Consecutive");
        }
        else
        {
            Console.WriteLine("Not Consecutive");                 
        }
    }
    static bool IsSequential(int[] array)
    {
        return array.Zip(array.Skip(1), (a, b) => (a + 1) == b).All(x => x);
    }

Solution 3:

Consider an approach like this:

    static void Main(string[] args)
    {
        Console.WriteLine("Enter numbers separate by hypen : ");
        var name = Console.ReadLine();
        var numarray = name.Split('-');
        var lower = int.Parse(numarray[0]);
        Console.WriteLine(Enumerable.Range(lower, numarray.Length)
            .Select(z => z.ToString()).SequenceEqual(numarray)
            ? "Consecutive"
            : "Not");

        Console.ReadLine();
    }

(Even better, use TryParse just in case the first entry is not a number)