• Home
  • Contents
  • About
​​​​​​​​​​​​​​​​

Friday 23 November 2012

Merging Multiple Arrays of equal size using LINQ

Merging arrays or collections implementing IEnumerable  can be  useful at times.

For example,consider two integer arrays of equal length .

int[] numArrOne = new int[] { 1, 2, 3, 4 };
int[] numArrTwo = new int[] { 5, 6, 7, 8 };

LINQ's zip can be used to merge them(the elements are added(merged) along their indices)
 

mergedNumbers will  now have the new elements   { 6, 8, 10, 12 }

But what if we want to merge Multiple Arrays and not just two? The Zip method only works with two sequences and not more than that.Ok so is there a way around?.Yes when you combine Aggregate and Zip together, you have what you need.

But first off you need to store all of the arrays on a single List

int[] numArrOne = new int[] { 1, 2, 3, 4 };
int[] numArrTwo = new int[] { 5, 6, 7, 8 };
int[] numArrThree = new int[] { 5, 6, 7, 8 }; 
List<int[]> numberStore = new List<int[]>() { numArrOne, numArrTwo, numArrThree };

LINQ

mergedNumbers will now have 11,14,17,20 after merging all three arrays.

This LINQ will merge any number of Arrays and will produce a single array.

The word Merging is quite broad and can take different meanings,depending on the type of elements you have in the collection.If you are running this same operation on arrays of strings,it is going to give a different meaning to the output.


CodeIgnoto


No comments:

Post a Comment