典型Skip
+ Take
溶液可以是像這樣:
public static IEnumerable<T[]> SplitArrayWithLinq<T>(T[] source, int size) {
if (null == source)
throw new ArgumentNullException("source");
else if (size <= 0)
throw new ArgumentOutOfRangeException("size", "size must be positive");
return Enumerable
.Range(0, source.Length/size + (source.Length % size > 0 ? 1 : 0))
.Select(index => source
.Skip(size * index)
.Take(size)
.ToArray());
}
如果您不允許使用的LINQ(Skip
以及Take
包括):
public static IEnumerable<T[]> SplitArray<T>(T[] source, int size) {
if (null == source)
throw new ArgumentNullException("source");
else if (size <= 0)
throw new ArgumentOutOfRangeException("size", "size must be positive");
int n = source.Length/size + (source.Length % size > 0 ? 1 : 0);
for (int i = 0; i < n; ++i) {
T[] item = new T[i == n - 1 ? source.Length - size * i : size];
Array.Copy(source, i * size, item, 0, item.Length);
yield return item;
}
}
測試(讓我們分裂[1, 2, ... 8, 9]
陣列爲4
項目組塊):
var source = Enumerable.Range(1, 9).ToArray();
var result = SplitArray(source, 4);
string report = String.Join(Environment.NewLine,
result.Select(item => String.Join(", ", item)));
// 1, 2, 3, 4
// 5, 6, 7, 8
// 9 // <- please, notice that the last chunk has 1 item only
Console.Write(report);
不要ü想要的數組一陽? –
爲什麼你不能使用'Skip'? – user3185569
清楚地說明你的問題。 Directory.GetFiles()可以很慢,是問題的核心嗎?因爲大家都在無視這一點。你是在數組上而不是在List <>上出售的? –