Home > Back-end >  Performing Actions With Pairs in Arrays/Lists in C#
Performing Actions With Pairs in Arrays/Lists in C#

Time:09-09

Sorry if the title's worded a bit weird but this is what I'm trying to get to.

Lets say you have an array of integers like this:

int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

What would be the best way to use this array to return a new array but with the values of each pair summed together, so using the array above, it would return

{ 3, 7, 11, 15, 19 }

Obviously you can so something basic like

int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var x = new List<int>();
for (int i=0;i<arr.Length;i =2)
    x.Add(arr[i]   arr[i 1]);

But if you want to keep your code concise and/or work with different items, this doesn't really seem like the best option.

So is there any other/better way to do this? I was testing some ideas with Enumerable.Aggregate but couldn't come up with anything, please share ideas.

CodePudding user response:

Well, your code is readable and efficien; however, you can generalize your current solution a bit:

  • Last array item(s) can well have no pair
  • We can combine not only pairs, but three or four items etc.

If you are looking for such kind of code for

int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

the modifiction of your solution can be:

const int size = 2;

int[] result = new int[arr.Length / size   Math.Sign(arr.Length % size)];

for (int i = 0; i < arr.Length;   i)
  result[i / size]  = arr[i];

For instance, if we set size = 3; then for we'll get { 6, 15, 24, 10 } as the result. Note, that the last group is incomplete:

   1, 2, 3, 4, 5, 6, 7, 8, 9, 10
   |     |  |     |  |     |  ||
      6        15       24    10

CodePudding user response:

I would argue that your approach is perfectly fine, but for LINQ you can do some stuff with Chunk:

var x = arr
    .Chunk(2)
    .Where(c => c.Length == 2)
    .Select(c => c.Sum())
    .ToArray();
  • Related