group successive numbers into the mass
-
There's an object.
List<int>
For example,var src = new List<int> {0,1,3,5,6,7,9};
There are no duplicates on the original list, that is.
{0,1,1,3,5}
Not considered. List pre-conditionedhow to write a function that will return the list of objects to which successive numbers will be applied, i.e. the following result is required:
var result = new List<List<int>> { new List<int> {0,1}, new List<int> {3}, new List<int> {5,6,7}, new List<int> {9} };
I'm just thinking about making it in the cycle.
for
But I think you can do it more. elegant usinglinq
-
The method may be used here. https://msdn.microsoft.com/ru-ru/library/bb549218(v=vs.110).aspx with an initial battery value.
src.Aggregate(new List<List<int>>(), (acc, cur) => { //проверяем что мы, либо зашли в первый раз, либо разница между элементами больше 1. if (acc.Count == 0 || cur - acc.Last().Last() > 1) { //добавляем новый список с текущим элементом acc.Add(new List<int> { cur }); } else { //иначе добавляем в последний список acc.Last().Add(cur); }
//возвращаем аккумулятор return acc;
});