如何按顺序中断拆分已排序的数字集合?
例如:
List<int> someList = new List<int>{1,2,3,7,8,9}
输出:
someDictionary[0].Key == 1;
someDictionary[0].Value == 3;
someDictionary[1].Key == 7;
someDictionary[1].Value == 9;
答案 0 :(得分:2)
如果我已经正确地理解了你,那么这样就可以解决问题
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;
}