Posted by: Cirilo Meggiolaro | 11/9/2008

Tip of the day #26 – Concatenating arrays with LINQ

A quick and lightweight tip for a Sunday morning: how to concatenate arrays using LINQ.

How to…

Let’s assume that your code contains two arrays and you need to loop through both collections to perform similar tasks. Instead of create two different loops you may use the Concat function to concatenate the arrays and to avoid duplicated code.

int[] myArray1 = {1, 5, 7, 10, 15, 16, 20, 25 };
int[] myArray2 = { 3, 4, 6, 7, 8, 9, 11, 13, 14, 16, 20 };

foreach (int item in myArray1.Concat(myArray2))

If you want to create a new object as a result of the concatenation, you may use a generic IEnumerable type to achieve that:

IEnumerable<int> myConcatArray = myArray1.Concat(myArray2);

Enjoy it!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: