Defining a simple class for storing results:
private class Set { public int Start = 0; public int Count = 0; }
You can use this method:
private static IEnumerable<Set> GetSets(List<int> src) { List<Set> rtn = new List<Set>(); int previous = int.MaxValue; foreach (int i in src) { if (i == previous + 1) { rtn[rtn.Count - 1].Count += 1; } else { rtn.Add(new Set() { Start = i, Count = 1 }); } previous = i; } return rtn; }
I'm not fond of the magic value of int.MaxValue , but it retains additional logic around the first iteration.
Calling GetSets(new List<int>() { 0, 1, 2, 6, 7, 10 }) correctly gives the desired result.
source share