加入不同长度的两个列表在C# [英] Add two Lists of different length in c#

查看:126
本文介绍了加入不同长度的两个列表在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

obvisouly我可以写一个循环,但有没有更好的办法? ?使用LINQ

obvisouly i can write a loop but is there a better way? using linq?

推荐答案

您可以使用修改后的拉链的操作很轻松了,但没有内置的是这样的:

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆