在c#中添加两个不同长度的List [英] Add two Lists of different length in c#
本文介绍了在c#中添加两个不同长度的List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
List<double> a = new List<double>{1,2,3};
List<double> b = new List<double>{1,2,3,4,5};
a + b 应该给我 2,4,6,4,5
a + b should give me 2,4,6,4,5
显然我可以写一个循环,但有更好的方法吗?使用 linq?
obvisouly i can write a loop but is there a better way? using linq?
推荐答案
你可以很容易地使用修改后的zip"操作,但没有内置.比如:
You could use a modified "zip" operation easily enough, but nothing built in. Something like:
static void Main() {
var a = new List<int> { 1, 2, 3 };
var b = new List<int> { 1, 2, 3, 4, 5 };
foreach (var c in a.Merge(b, (x, y) => x + y)) {
Console.WriteLine(c);
}
}
static IEnumerable<T> Merge<T>(this IEnumerable<T> first,
IEnumerable<T> second, Func<T, T, T> operation) {
using (var iter1 = first.GetEnumerator())
using (var iter2 = second.GetEnumerator()) {
while (iter1.MoveNext()) {
if (iter2.MoveNext()) {
yield return operation(iter1.Current, iter2.Current);
} else {
yield return iter1.Current;
}
}
while (iter2.MoveNext()) {
yield return iter2.Current;
}
}
}
这篇关于在c#中添加两个不同长度的List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文