James Jeffery
James Jeffery

Reputation: 12599

Combine each element from Array 1 with each element from Array 2

I'll keep this simple. My dataset is as follows:

Array 1:

James
Bob
Jim

Array 2:

0
1
2

I want to create a new array by joining the two arrays so they produce something like the following:

James 0
James 1
James 2
Bob 0
Bob 1
Bob 2
Jim 0
Jim 1
Jim 2

How can it be done in C#. I've came into this problem before, I remember using extension methods but I have no idea what area of Set Theory this falls under.

Upvotes: 3

Views: 208

Answers (4)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

You would use a cross join (Cartesian product):

var result = from x in array1
             from y in array2
             select string.Format("{0} {1}", x, y);

See it live: http://ideone.com/1TdKGy

Upvotes: 5

terrybozzio
terrybozzio

Reputation: 4532

This is another way to go:

            string[] names = { "James", "Bob", "Jim" };
            int[] numbers = { 0, 1, 2 };
            string[] result = new string[names.Length * 3];
            for (int i = 0, y = 0 ; i < result.Length; i+=3,y++)
            {
                result[i] = names[y] + numbers[0].ToString();
                result[i + 1] = names[y] + numbers[1].ToString();
                result[i + 2] = names[y] + numbers[2].ToString();
            }

Upvotes: 0

Learner
Learner

Reputation: 4004

You need Cartesian Join or Cross Join. One more way to do it using SelectMany:

var arr1 = new string [] {"James","Bob","Jim"};
var arr2 = new int [] { 1, 2, 3};

var query = arr1.SelectMany(x => arr2, (x, y) => new { x, y });

foreach(var item in query)
{
  Console.WriteLine(item);
}

Upvotes: 1

usr
usr

Reputation: 171246

You're looking for a cross product:

from a in a1
from b in a2
select new { a, b }

Upvotes: 6

Related Questions