动态压缩 n 列表



我已经看到了这样的解决方案,可以在编译时zip已知数量的List大于两个Lists:

public static class MyFunkyExtensions
{
public static IEnumerable<TResult> ZipThree<T1, T2, T3, TResult>(
this IEnumerable<T1> source,
IEnumerable<T2> second,
IEnumerable<T3> third,
Func<T1, T2, T3, TResult> func)
{
using (var e1 = source.GetEnumerator())
using (var e2 = second.GetEnumerator())
using (var e3 = third.GetEnumerator())
{
while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
yield return func(e1.Current, e2.Current, e3.Current);
}
}
}

如果您有List<List<>>并且想要动态压缩它们,正确的代码是什么?请注意,列表的数量在编译时是未知的。我不想创建一个ZipFour,ZipFive等...

像这样的东西?

public static IEnumerable<TResult> ZipAll<T, TResult>(
IEnumerable<IEnumerable<T>> lists,
Func<IEnumerable<T>, TResult> func)
{
var enumerators = lists.Select(l => l.GetEnumerator()).ToArray();
while(enumerators.All(e => e.MoveNext()))
{   
yield return func(enumerators.Select(e => e.Current));
}
foreach (var enumerator in enumerators)
{
enumerator.Dispose();
}
}

这假设每个列表/枚举的类型参数是相同的(即你想在类似List<List<int>>上调用它。如果不是这种情况,则需要改用非通用IEnumerable(并在最后删除foreach,因为非通用IEnumerable不是一次性的)。

我还没有对此进行大量测试;有兴趣看看评论者可能会在其中戳出什么样的漏洞。

编辑:

  • 正如 MineR 所指出的,此实现不会捕获示例实现中using语句的效果。有几种不同的方法可以修改它以使用 try/final(或多次 try/finals),具体取决于您希望如何处理在GetEnumeratorMoveNextCurrentDispose中可能发生的异常。
  • 此外,虽然可以压缩无限长度的枚举,但从概念上讲,Zip需要有限数量的这些枚举。如果listsICollection<IEnumerable<T>>型,可能会更正确。如果lists是无限的,这将引发OutOfMemory异常。
  • 经过一番讨论:一个具体要求是能够在选择器函数中使用索引器。这可以通过使第三个参数Func<IList<T>, TResult>而不是Func<IEnumerable<T>, TResult>来实现,并向enumerators.Select(e => e.Current)添加一个ToArray()

如果不知道要如何压缩列表,则很难编写确切的解决方案,但您可以执行以下操作:

List<int> ListOne = new List<int> { 1, 2, 3, 4, 5 };
List<int> ListTwo = new List<int> { 123, 12, 3243, 223 };
List<int> ListThree = new List<int> { 23, 23, 23, 23, 23, 23 };
var AllLists = new List<List<int>> { ListOne, ListTwo, ListThree };
var result = AllLists.Aggregate((acc, val) => acc.Zip(val, (init, each) => init + each).ToList());

您传递给 Zip 函数的函数显然是您想要处理 Zipping 的,在这种情况下,整数只是相加,但字符串可以连接等。聚合函数将用于枚举所有列表,并将结果合并到单个容器中,在本例中为 List。

最新更新