Habibillah
Habibillah

Reputation: 28685

How do I join an array by addition operation in C#?

I have two array definition and I want to do addition operation element by element without looping operation? for example:

decimal[] xx = { 1, 2, 3 };
decimal[] yy = { 6, 7, 8 };

the result I want is:

decimal[] zz = { 7, 9, 11 };

the addition operation is simple. Just add one by one for each element like

decimal[] zz = decimal[xx.Length];
for (int i=0; i<xx.Length;i++){
   zz[i] =xx[i] + yy[i];
}

But I don't want to use looping operation.

Upvotes: 0

Views: 184

Answers (6)

Rawling
Rawling

Reputation: 50104

You can use LINQ:

var zz = Enumerable
             .Range(0, (int)Math.Min(xx.Length, yy.Length))
             .Select(i => xx[i] + yy[i])
             .ToArray();

but that's really just moving the looping behind-the-scenes.

Upvotes: 2

Guffa
Guffa

Reputation: 700152

You can't do that without looping some way or the other.

Your array creation and loop should be:

decimal[] zz = new decimal[xx.Length];
for (int i = 0; i < xx.Length; i++){
   zz[i] = xx[i] + yy[i];
}

Or a more compact, but somewhat less readable version:

decimal[] zz = new decimal[xx.Length];
for (int i = 0; i < xx.Length; zz[i++] = xx[i] + yy[i]);

You can also use Linq extensions to do the looping:

decimal[] zz = xx.Select((x, i) => x + yy[i]).ToArray();

Or:

decimal[] zz = Enumerable.Range(0, xx.Length).Select(i => xx[i]+yy[i]).ToArray();

Upvotes: 2

cuongle
cuongle

Reputation: 75296

Another way using Enumerable.Range beside Zip:

var result = Enumerable.Range(0, xx.Length)
                       .Select(i => xx[i] + yy[i])
                       .ToArray();

Upvotes: 2

L.B
L.B

Reputation: 116098

  var zz = xx.Select((x, i) => x + yy[i]).ToArray();

Upvotes: 3

Darius
Darius

Reputation: 5259

If they are globally scoped arrays you could use recursion

public void add(int index){

  zz[index] = xx[index] + yy[index];

  if(index < xx.Length){
     add(index+1);

   }

}

Is psuedo-code, untested, but represents general idea. Let me know your thoughts.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460018

You can use Enumerable.Zip:

decimal[] zz = xx.Zip(yy, (x, y) => x + y).ToArray();

Upvotes: 9

Related Questions