c# - 如何使用 LINQ 转置二维集合中的维度?

标签 c# linq

考虑以下结构:

IEnumerable<IEnumerable<int>> collection = new[] { 
    new [] {1, 2, 3}, 
    new [] {4, 5, 6}, 
    new [] {7, 8, 9} 
};

如何枚举此集合以获得 IEnumerable<int>由第一项、第二项等组成的集合?

即 {1, 4, 7}, {2, 5, 8}, ...

(虽然我选择的实现是 int[] 对象,但假设您只有 IEnumerable<int> 功能。谢谢。)

最佳答案

这是一种使用生成器而不是递归的方法。数组构造也较少,因此它可能更快,但这完全是推测。

public static IEnumerable<IEnumerable<T>> Transpose<T>(
    this IEnumerable<IEnumerable<T>> @this) 
{
    var enumerators = @this.Select(t => t.GetEnumerator())
                           .Where(e => e.MoveNext());

    while (enumerators.Any()) {
        yield return enumerators.Select(e => e.Current);
        enumerators = enumerators.Where(e => e.MoveNext());
    }
}

关于c# - 如何使用 LINQ 转置二维集合中的维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10554866/

相关文章:

c# - 在 C# 中从 '\ud835' 格式转换为 "𝓛"[UWP]

c# - System.NotSupportedException 目前不支持方法 'System.Linq.Queryable.GroupBy' 的这种重载。

.net - 将 IEnumerable 转换为列表

vb.net linq查询where子句中的iif条件

c# - 命名管道包装库工作示例

c# - 在CSS声明中使用session

c# - 为什么 visual studio 不在应用程序退出时退出调试器?

c# - new 和 override 的区别?

asp.net - Linq 无法识别查询中的解析

c# - 选择子句问题中的动态列