考虑以下结构:
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/