【问题标题】:merging 2 string lists合并 2 个字符串列表
【发布时间】:2014-07-10 21:25:21
【问题描述】:

假设我有 2 个列表

List<string> list1 = new List<string>;
list1.Add("one");
list1.Add("three");
list1.Add("five");

List<string> list2 = new List<string>;
list2.Add("two");
list2.Add("four");
list2.Add("six");

我怎样才能合并它们(技术上不是连接),以便我可以得到一个包含值的新列表:

[one two] [three four] [five six]

请注意,'[' 和 ']' 分隔最终列表中的每个字符串。所以列表中的第一个值是“一二”,第二个值是“三四”,第三个值是“五六”。

我希望我解释清楚了。

【问题讨论】:

  • 好像你在找Enumerable.Zip()。
  • @HighCore 正是我所需要的。谢谢。

标签: c# list


【解决方案1】:

你要的Linq函数是Zip:

var list3 = list1.Zip(list2, (s1, s2) => s1 + " " + s2);

输出:

IEnumerable<String> (3 items)
---------------
one two 
three four 
five six 

【讨论】:

  • 出于好奇,如果您的列表中有不同数量的项目会怎样?
  • 它将组合元素,直到其中一个集合用完项目。
  • 其他元素将被丢弃。查看上面链接中的文档。它有一个样本。
  • 糟糕,没有意识到这是一个链接。谢谢!
  • @DStanley 谢谢,正是我想要的。
猜你喜欢
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多