i want to find all possible sequence elements from list using c#
numbers are in incremental order if it is sequence i have to split the array
Example array : int[] array = {1,2,3,5,6,8,9,10}
expected output as all possible sequence list: {1,2,3} , {5,6} ,{8,9,10}
Can someone help me on this ?
code
for(int i=0;i<array.Length;i++)
{
if(array[i]== array[i+1])
{
// i want to get all possible sequence of elements
}
}
Run Code Online (Sandbox Code Playgroud)
private static List<List<int>> FindSequence(int[] array)
{
var result = new List<List<int>>();
var tempList = new List<int>{array[0]};
var lastResult = array[0];
for (var i = 1; i < array.Length; i++)
{
if(lastResult + 1 == array[i])
tempList.Add(array[i]);
else
{
result.Add(tempList);
tempList = new List<int> {array[i]};
}
lastResult = array[i];
}
result.Add(tempList);
return result;
}
Run Code Online (Sandbox Code Playgroud)
我曾经用过List<List<int>>
,可以根据需要更改List<int[]>
为。
归档时间: |
|
查看次数: |
102 次 |
最近记录: |