我有三个(有可能有3-4个以上泛型列表,但在本例中是3个)泛型列表。
List<string> list1
List<string> list2
List<string> list3
所有列表具有相同数量的元素(相同计数)。
我用ZIP将两个列表组合在一起:
var result = list1.Zip(list2, (a, b) => new {
test1 = f,
test2 = b
}
我对foreach
使用了那个语句,以避免foreach
的每一个List,像
foreach(var item in result){
Console.WriteLine(item.test1 + " " + item.test2);
}
如何使用Simmilary与Zip的三个列表?
谢谢
编辑:
我想要:
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调试模式下)
[0] { a = {"test"},
b = {"item"},
c = {"value"}
}
[1] { a = {"otherTest"},
b = {"otherItem"},
c = {"otherValue"}
}
那怎么办呢?
8条答案
按热度按时间o2g1uqev1#
对我来说,最明显的方法是使用
Zip
两次。例如,
将合并(添加)三个
List<int>
对象的元素。更新日期:
您可以定义一个新的扩展方法,其作用类似于具有三个
IEnumerable
的Zip
,如下所示:用法(在与上面相同的上下文中)现在变为:
类似地,您的三个列表现在可以与以下内容组合:
cdmah0mi2#
There is another quite interesting solution that I'm aware of. It's interesting mostly from educational perspective but if one needs to perform zipping different counts of lists A LOT, then it also might be useful.
This method overrides .NET's LINQ
SelectMany
function which is taken by a convention when you use LINQ's query syntax. The standardSelectMany
implementation does a Cartesian Product. The overrided one can do zipping instead. The actual implementation could be:It looks a bit scary but it is a logic of zipping which if written once, can be used in many places and the client's code look pretty nice - you can zip any number of
IEnumerable<T>
using standard LINQ query syntax:If you then execute:
You will get:
You should keep this extension private within your class because otherwise you will radically change behavior of surrounding code. Also, a new type will be useful so that it won't colide with standard LINQ behavior for IEnumerables.
For educational purposes I've created once a small c# project with this extension method + few benefits: https://github.com/lukiasz/Zippable
Also, if you find this interesting, I strongly recommend Jon Skeet's Reimplementing LINQ to Objects articles .
Have fun!
aor9mmx13#
您可以在C#中使用级联zip方法、匿名类和元组结果合并许多列表。
其结果是:
5rgfhyps4#
使用**.NET 6**
..和超过
Zip
的元素可以用来产生一个由三个指定序列中的元素组成的元组序列。[doc]a7qyws3x5#
这是我们需要决定是否支持可读性更好的代码而不是更短的代码的情况之一。
nmpmafwu6#
用于压缩任意数量的不同大小列表的通用解决方案:
wh6knrhe7#
您可以将这些
List<string>
合并为List<List<string>>
并对其进行聚合测试结果
请参阅dotnetfiddle.net
yks3o0rb8#
使用匿名元组的解决方案(我认为是. Net 4或更高版本):