我有两个这样的名单:
a1, a2, a3, ..
和
b1, b2, b3, ..
如何将它们混合起来得到这样的结果?:
a1, b1, a2, b2, ..
我想到了这一点,但我不喜欢它:
for (int i = 0; i < List1.Count; i++)
{
FinalList.Add(List1[i]));
if (i < List2.Count)
FinalList.Add(List2[i]));
}
if (List1.Count < List2.Count)
{
for (int i = List1.Count; i < List2.Count; i++)
{
FinalList.Add(List2[i]);
}
}
答案 0 :(得分:2)
您可zip匹配两个序列的一部分,然后concat其余最长序列:
var FinalList = List1.Zip(List2, (a,b) => new [] { a, b })
.SelectMany(x => x)
.Concat(List1.Count < List2.Count ? List2.Skip(List1.Count) : List1.Skip(List2.Count))
.ToList();
如果你想要更有效的东西,那么你可以编写自己的扩展方法
public static IEnumerable<T> Merge<T>(this IEnumerable<T> source1, IEnumerable<T> source2)
{
// null-check here
using(var enumerator1 = source1.GetEnumerator())
using(var enumerator2 = source2.GetEnumerator())
{
bool hasItem1, hasItem2;
do
{
if (hasItem1 = enumerator1.MoveNext()) yield return enumerator1.Current;
if (hasItem2 = enumerator2.MoveNext()) yield return enumerator2.Current;
}
while (hasItem1 || hasItem2);
}
}
用法:
var finalList = List1.Merge(List2).ToList();
答案 1 :(得分:1)
这对我有用:
var List1 = new [] { "a1", "a2", "a3" };
var List2 = new [] { "b1", "b2", "b3" };
var mix =
List1
.Zip(List2, (l1, l2) => new [] { l1, l2 })
.SelectMany(x => x);
它给出了:
a1 b1 a2 b2 a3 b3