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/

10-12 06:38