使用LINQ如何使用元素索引转换列表列表 [英] Using LINQ how to transform a List of Lists using elements index
本文介绍了使用LINQ如何使用元素索引转换列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用LINQ将列表列表转换为新的列表列表,其中每个列表都包含来自同一索引的所有元素.
using LINQ how can I transform a List of Lists to a new List of Lists where each list has all the elements from the same index.
例如
l[0] = {3,15,22,6}
l[1] = {9,81,52,7}
l[2] = {2,0,32,73}
将变成
l[0] = {3,9,2}
l[1] = {15,81,0}
l[2] = {22,52,32}
l[3] = {6,7,73}
谢谢
推荐答案
您可以在答案中使用此Transpose
扩展方法由dtb 撰写(我将处置方式从Array.ForEach
更改为foreach
,因为我发现它更清晰了,并且
You can use this Transpose
extension method, from an answer by dtb (I changed the disposing from Array.ForEach
to foreach
because I find it clearer, and I'm not the only one who doesn't think ForEach
methods like that should be used):
public static IEnumerable<IList<T>> Transpose<T>(
this IEnumerable<IEnumerable<T>> source)
{
var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
try
{
while (enumerators.All(e => e.MoveNext()))
{
yield return enumerators.Select(e => e.Current).ToArray();
}
}
finally
{
foreach (var enumerator in enumerators)
enumerator.Dispose();
}
}
// e.g.
IList<IList<int>> l = new int[3][];
l[0] = new []{0,1,2,3};
l[1] = new []{4,5,6,7};
l[2] = new []{8,9,10,11};
l = l.Transpose().ToList();
// l is { { 0, 4, 8 }, { 1, 5, 9 }, { 2, 6, 10 }, { 3, 7, 11 } }
这篇关于使用LINQ如何使用元素索引转换列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文