Adding/summing two arrays

前端 未结 5 1328
抹茶落季
抹茶落季 2021-01-31 02:51

I\'ve encountered a purely hypothetical problem which feels like it has an easy solution if I find the right linq method...

I have two arrays of ints and I know they are

相关标签:
5条回答
  • 2021-01-31 02:59

    Zip it :)

    var a = new int[] {1,2,3 };
    var b = new int[] {4,5,6 };
    a.Zip(b, (x, y) => x + y)
    
    0 讨论(0)
  • 2021-01-31 03:03

    You can use the Select method.

    int[] a = new[] { 1, 2, 3 };
    int[] b = new[] { 10, 20, 30 };
    
    var c = a.Select ((x, index) => x + b[index]).ToArray();
    
    0 讨论(0)
  • 2021-01-31 03:03

    Without LINQ:

    private static IEnumerable<int> AddArrays(IEnumerable<int> a1, IEnumerable<int> a2)
    {
        var e1 = a1.GetEnumerator();
        var e2 = a2.GetEnumerator();
    
        while (e1.MoveNext() && e2.MoveNext())
            yield return e1.Current + e2.Current;
    }
    
    0 讨论(0)
  • 2021-01-31 03:08
    public static int[] AddArrays(int[] a, int[] b)
    
    {
         return a.Zip(b, (x,y) => x+y).ToArray();
    }
    
    0 讨论(0)
  • 2021-01-31 03:14
    IList<int> first = new List<int> { 2, 3, 4, 5 };
    IList<int> second = new List<int> { 2, 3, 4, 5 };
    
    var result = Enumerable.Zip(first, second, (a, b) => a + b);
    
    0 讨论(0)
提交回复
热议问题