Ami*_*abh 19 c# linq arrays .net-4.0
在c#4中将数组分组为n个元素数组的列表的最佳方法是什么?
例如
string[] testArray = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8" };
Run Code Online (Sandbox Code Playgroud)
如果我们采用n = 3,应该拆分成.
string[] A1 = {"s1", "s2", "s3"};
string[] A2 = {"s4", "s5", "s6"};
string[] A3 = {"s7", "s8"};
Run Code Online (Sandbox Code Playgroud)
使用LINQ可能是一种简单的方法吗?
kbr*_*ton 25
这将生成一个包含3个元素的字符串数组:
int i = 0;
var query = from s in testArray
let num = i++
group s by num / 3 into g
select g.ToArray();
var results = query.ToArray();
Run Code Online (Sandbox Code Playgroud)
我不认为有一个很好的内置方法,但你可以编写如下的方法.
public static IEnumerable<IEnumerable<T>> GroupInto<T>(
this IEnumerable<T> source,
int count) {
using ( var e = source.GetEnumerator() ) {
while ( e.MoveNext() ) {
yield return GroupIntoHelper(e, count);
}
}
}
private static IEnumerable<T> GroupIntoHelper<T>(
IEnumerator<T> e,
int count) {
do {
yield return e.Current;
count--;
} while ( count > 0 && e.MoveNext());
}
Run Code Online (Sandbox Code Playgroud)
int size = 3;
var results = testArray.Select((x, i) => new { Key = i / size, Value = x })
.GroupBy(x => x.Key, x => x.Value, (k, g) => g.ToArray())
.ToArray();
Run Code Online (Sandbox Code Playgroud)
如果您不介意输入结果IEnumerable<IEnumerable<T>>
而不是T[][]
那么您可以ToArray
完全省略调用:
int size = 3;
var results = testArray.Select((x, i) => new { Key = i / size, Value = x })
.GroupBy(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)