如何在 C# Zip 中组合两个以上的通用列表? [英] How to combine more than two generic lists in C# Zip?
问题描述
我有三个(可能有超过 3-4 个通用列表,但在本例中让 3 个)通用列表.
I have three (it's possible to have more than 3-4 generic list, but in this example let 3) generic lists.
List<string> list1
List<string> list2
List<string> list3
所有列表都具有相同数量的元素(相同的计数).
all lists have same number of elements (same counts).
我用它来将两个列表与 ZIP 结合起来:
I used that for combining two lists with ZIP :
var result = list1.Zip(list2, (a, b) => new {
test1 = f,
test2 = b
}
我将其用于 foreach
语句,以避免 foreach
每个 List,例如
I used that for foreach
statement, to avoid foreach
each List, like
foreach(var item in result){
Console.WriteLine(item.test1 + " " + item.test2);
}
如何将 simmilary 与 Zip 用于三个列表?
How to use simmilary with Zip for three lists ?
谢谢
我想要:
List<string> list1 = new List<string>{"test", "otherTest"};
List<string> list2 = new List<string>{"item", "otherItem"};
List<string> list3 = new List<string>{"value", "otherValue"};
ZIP后(我不知道方法),我想要结果(在VS2010调试模式下)
after ZIP (I don't know method), I want to result (in VS2010 debug mode)
[0] { a = {"test"},
b = {"item"},
c = {"value"}
}
[1] { a = {"otherTest"},
b = {"otherItem"},
c = {"otherValue"}
}
怎么做?
推荐答案
对我来说最明显的方法是使用 Zip
两次.
The most obvious way for me would be to use Zip
twice.
例如
var results = l1.Zip(l2, (x, y) => x + y).Zip(l3, (x, y) => x + y);
将组合(添加)三个 List
对象的元素.
would combine (add) the elements of three List<int>
objects.
更新:
您可以定义一个新的扩展方法,它的作用类似于带有三个 IEnumerable
的 Zip
,如下所示:
You could define a new extension method that acts like a Zip
with three IEnumerable
s, like so:
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);
}
}
}
用法(在与上述相同的上下文中)现在变为:
The usage (in the same context as above) now becomes:
var results = l1.ZipThree(l2, l3, (x, y, z) => x + y + z);
同样,您现在可以将三个列表组合在一起:
Similarly, you three lists can now be combined with:
var results = list1.ZipThree(list2, list3, (a, b, c) => new { a, b, c });
这篇关于如何在 C# Zip 中组合两个以上的通用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!