我有两个不同长度的List.我想要实现的是第三个List,其中包含list1中的第一个元素,然后是list2中的第一个元素,然后是list1中的第二个元素,以及list2中的第二个元素,依此类推,直到其中一个元素用尽(它们为止) "不均匀",然后只需添加该列表中的任何剩余项目.
结果应该与list1和list2组合的项目数相同.
我不能使用类似Union.ToList()的东西,因为它没有交织两者,它只是将例如list1中的所有项添加到list2的底部并输出结果.我试过.Zip(Linq)然而,似乎接受了两个元素并将它们合并为一个元素(即将两个字符串连接成一个更长的字符串).
List<string> list1 = new List<string>(){
"4041",
"4040"
};
List<string> list2 = new List<string>(){
"4039",
"4044",
"4075",
"4010",
"4100",
"4070",
"4072"
};
// Ideal result:
result = { "4041",
"4039",
"4040"
"4044",
"4075",
"4010",
"4100",
"4070",
"4072"
};
Run Code Online (Sandbox Code Playgroud)
int length = Math.Min(list1.Count, list2.Count);
// Combine the first 'length' elements from both lists into pairs
list1.Take(length)
.Zip(list2.Take(length), (a, b) => new int[] { a, b })
// Flatten out the pairs
.SelectMany(array => array)
// Concatenate the remaining elements in the lists)
.Concat(list1.Skip(length))
.Concat(list2.Skip(length));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1388 次 |
| 最近记录: |