我有一个有序的数字数组{1,2,3,4,5,9,10,11,13}。 需要将它们分组为:{1,2,3,4,5},{9,10,11},{13}。 我使用for循环来解决这个问题:
// An ordered array
int[] numbers = {1, 2, 3, 4, 5, 9, 10, 11, 13};
List<List<int>> listOfGroupNum = new List<List<int>>();
List<int> listofNumbers = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
// Take two numbers
// If a difference betwen them -1 adding to a group
if (((i + 1) < numbers.Length) && (numbers[i] - numbers[i + 1] == -1))
{
listofNumbers.Add(numbers[i]);
continue;
}
listofNumbers.Add(numbers[i]);
listOfGroupNum.Add(listofNumbers);
listofNumbers = new List<int>();
}
有没有办法使用Linq解决这个问题?
更新 我找到了一个LINQ表达式,回答我的问题:
int[] numbers = {1, 2, 3, 4, 5, 9, 10, 11, 13};
var groups =
numbers.Select((x, i) => new {Difference = i - x, Value = x})
.GroupBy(x => x.Difference)
.Select(x => x.Select(y => y.Value).ToList()).ToList();