LINQ到对象 - 从数字列表返回数对 [英] Linq to Objects - return pairs of numbers from list of numbers

查看:133
本文介绍了LINQ到对象 - 从数字列表返回数对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 = { {1, 2}, {3, 4}, {5, 6}, {7, 0} }

对的元素应该是两个元素的列表,或者一些匿名的类的实例有两个字段,像新{一= 1,二= 2}

The elements of pairs should be either two-element lists, or instances of some anonymous class with two fields, something like new {First = 1, Second = 2}.

推荐答案

默认LINQ方法都不能做到这一点懒洋洋地,并用单次扫描。与自身荏苒序列做2次扫描和分组并非完全懒惰。最好的办法就是直接执行它:

None of the default linq methods can do this lazily and with a single scan. Zipping the sequence with itself does 2 scans and grouping is not entirely lazy. Your best bet is to implement it directly:

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;
}

这篇关于LINQ到对象 - 从数字列表返回数对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆