List dansConList = new List();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;
List dansRandomList = new List
One-liner, only iterates until the first non-consecutive element:
bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any();
Update: a couple examples of how this works:
Input is { 5, 6, 7, 8 }
Select yields { (5-0=)5, (6-1=)5, (7-2=)5, (8-3=)5 }
Distinct yields { 5, (5 not distinct, 5 not distinct, 5 not distinct) }
Skip yields { (5 skipped, nothing left) }
Any returns false
Input is { 1, 2, 6, 7 }
Select yields { (1-0=)1, (2-1=)1, (6-2=)4, (7-3=)4 } *
Distinct yields { 1, (1 not distinct,) 4, (4 not distinct) } *
Skip yields { (1 skipped,) 4 }
Any returns true
* The Select will not yield the second 4 and the Distinct will not check it, as the Any will stop after finding the first 4.
It is works for unique list only.
List<Int32> dansConList = new List<Int32>();
dansConList.Add(7);
dansConList.Add(8);
dansConList.Add(9);
bool b = (dansConList.Min() + dansConList.Max())*((decimal)dansConList.Count())/2.0m == dansConList.Sum();
var result = list
.Zip(list.Skip(1), (l, r) => l + 1 == r)
.All(t => t);
Extension method:
public static bool IsConsecutive(this IEnumerable<int> myList)
{
return myList.SequenceEqual(Enumerable.Range(myList.First(), myList.Last()));
}
Useage:
bool isConsecutive = dansRandomList.IsConsecutive();
Here is an extension method that uses the Aggregate
function.
public static bool IsConsecutive(this List<Int32> value){
return value.OrderByDescending(c => c)
.Select(c => c.ToString())
.Aggregate((current, item) =>
(item.ToInt() - current.ToInt() == -1) ? item : ""
)
.Any();
}
Usage:
var consecutive = new List<Int32>(){1,2,3,4}.IsConsecutive(); //true
var unorderedConsecutive = new List<Int32>(){1,4,3,2}.IsConsecutive(); //true
var notConsecutive = new List<Int32>(){1,5,3,4}.IsConsecutive(); //false
In order to check whether the series contain consecutive number or not you may use this
Sample
isRepeatable(121878999, 2);
Result = True
since 9 repeats two times , where upto is no of times in series
isRepeatable(37302293, 3)
Result = False
since no number repeat 3 times in series
static bool isRepeatable(int num1 ,int upto)
{
List<int> myNo = new List<int>();
int previous =0;
int series = 0;
bool doesMatch = false;
var intList = num1.ToString().Select(x => Convert.ToInt32(x.ToString())).ToList();
for (int i = 0; i < intList.Count; i++)
{
if (myNo.Count==0)
{
myNo.Add(intList[i]);
previous = intList[i];
series += 1;
}
else
{
if (intList[i]==previous)
{
series += 1;
if (series==upto)
{
doesMatch = true;
break;
}
}
else
{
myNo = new List<int>();
previous = 0;
series = 0;
}
}
}
return doesMatch;
}