本文介绍了按值按顺序拆分数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简便的方法(linq?)根据连续的数字序列将int
数组拆分为新数组?例如,给出此伪代码:
Is there an easy (linq?) way to split an int
array into new arrays based off unbroken numerical sequences? For example given this pseudo code:
[Fact]
public void ArraySpike()
{
var source = new[] {1, 2, 3, 7, 8, 9, 12, 13, 24};
var results = SplitArray(source);
Assert.True(results[0] == new[] {1, 2, 3});
Assert.True(results[1] == new[] {7, 8, 9});
Assert.True(results[2] == new[] {12, 13});
Assert.True(results[3] == new[] {24});
}
public int[][] SplitArray(int[] source)
{
return source.???
}
推荐答案
这可以与linq扩展名Aggregate
一起使用.我的播种不是很优雅,但很容易更改. results
变量将包含数组的数组,并且它们实际上是List<T>
类型的,因为这样,它们可以很容易地在其中array []始终具有固定大小的函数中增长.
This can work with the linq extension Aggregate
. My seeding is not very elegant but that is easy enough to change. The results
variable will contain the array of arrays and they are actually of type List<T>
because that way they can be easily grown in the function where an array [] is always of fixed size.
这还假定源已经被订购并且是唯一的,如果不是这种情况,请添加.OrderBy(x => x).Distinct()
var source = new[] { 1, 2, 3, 7, 8, 9, 12, 13, 24 };
var results = new List<List<int>>{new List<int>()};
var temp = source.Aggregate(results[0], (b, c) =>
{
if (b.Count > 0 && b.Last() != c - 1)
{
b = new List<int>();
results.Add(b);
}
b.Add(c);
return b;
});
这篇关于按值按顺序拆分数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!