c# - Linq to Objects - 从数字列表中返回数字对

标签 c# linq linq-to-objects aggregate slice

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/

相关文章:

c# - 使用命令列表解析自定义文件

c# - 为什么泛型类型在方法签名中出现两次?

c# - 为什么 ToLookup 和 GroupBy 不同?

c# - 如何以有效的方式解析此 xml?

C# 合并 2 个字典

c# - Find() 与 Where().FirstOrDefault()

c# - 使用 Linq 索引属性?

c# - ScrollViewer 不使用 UWP Windows 10 Phone 滚动

c# - 这 2 个 LINQ 语句有什么区别?

C# 输入字符串的格式不正确