说我有以下数据
IEnumerable<IEnumerable<int>> items = new IEnumerable<int>[] {
new int[] { 1, 2, 3, 4 },
new int[] { 5, 6 },
new int[] { 7, 8, 9 }
};
Run Code Online (Sandbox Code Playgroud)
返回包含交错项的平面列表的最简单方法是什么,以便得到结果:
1,5,7,2,6,8,3,9,4
注意:运行时不知道内部列表的数量.
dtb*_*dtb 10
您所描述的内容本质上是一种转置方法,其中包含悬垂项目并且结果被展平.这是我的尝试:
static IEnumerable<IEnumerable<T>> TransposeOverhanging<T>(
this IEnumerable<IEnumerable<T>> source)
{
var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
try
{
T[] g;
do
{
yield return g = enumerators
.Where(e => e.MoveNext()).Select(e => e.Current).ToArray();
}
while (g.Any());
}
finally
{
Array.ForEach(enumerators, e => e.Dispose());
}
}
Run Code Online (Sandbox Code Playgroud)
例:
var result = items.TransposeOverhanging().SelectMany(g => g).ToList();
// result == { 1, 5, 7, 2, 6, 8, 3, 9, 4 }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1591 次 |
最近记录: |