var nums = new[]{ 1, 2, 3, 4, 5, 6, 7};
var pairs = /* some linq magic here*/ ;
=> 对 = { {1, 2}, {3, 4}, {5, 6}, {7, 0} }
pairs
的元素应该是双元素列表,或者是一些具有两个字段的匿名类的实例,比如 new {First = 1, Second = 2}
.
最佳答案
默认的 linq 方法都不能通过单次扫描懒惰地执行此操作。压缩序列本身会进行 2 次扫描,并且分组并不完全是惰性的。最好的办法是直接实现它:
public static IEnumerable<T[]> Partition<T>(this IEnumerable<T> sequence, int partitionSize) {
Contract.Requires(sequence != null)
Contract.Requires(partitionSize > 0)
var buffer = new T[partitionSize];
var n = 0;
foreach (var item in sequence) {
buffer[n] = item;
n += 1;
if (n == partitionSize) {
yield return buffer;
buffer = new T[partitionSize];
n = 0;
}
}
//partial leftovers
if (n > 0) yield return buffer;
}
关于c# - Linq to Objects - 从数字列表中返回数字对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4461367/