tags:

views:

33

answers:

1

How to split a sorted collection of numbers by interruption in sequence ?

eg.:

List<int> someList = new List<int>{1,2,3,7,8,9}

output :

someDictionary[0].Key == 1;
someDictionary[0].Value == 3;

someDictionary[1].Key == 7;
someDictionary[1].Value == 9;
+2  A: 

If I have understood you correctly something like this may do the trick

    private static List<List<int>> splitBySeq(List<int> someList)
    {
        //Stores the result
        List<List<int>> result = new List<List<int>>();

        //Stores the current sequence
        List<int> currentLst = new List<int>();
        int? lastNumber = null;

        //Iterate the items
        for (int i = 0; i < someList.Count; i++)
        {
            //If the have a "break" in the sequence and this isnt the first item
            if (lastNumber != null && someList[i] != lastNumber + 1)
            {
                result.Add(currentLst);
                currentLst = new List<int>();
            }

            currentLst.Add(someList[i]);
            lastNumber = someList[i];
        }

        if (currentLst.Count != 0)
            result.Add(currentLst);

        return result;
    }
Mikael