Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- public class CartesianProductSelectManyExample
- {
- public static void Main(string[] args)
- {
- var abcArray = new string[]{"a", "b", "c"};
- var xyzArray = new string[]{"x", "y", "z"};
- var combos = CartesianProductSmart(abcArray, xyzArray);
- foreach(var combo in combos)
- {
- Console.WriteLine(string.Format("[{0},{1}]", combo[0], combo[1]));
- }
- }
- private static string[][] CartesianProductSmart(string[] arr1, string[] arr2)
- {
- // for each s1 in arr1, extract arr2,
- // then pass s1 and s2 into a newly-made string array.
- return arr1.SelectMany(s1 => arr2, (s1, s2) => new string[]{s1, s2})
- .ToArray();
- }
- private static string[][] CartesianProductDumb(string[] arr1, string[] arr2)
- {
- // the dumb way; nested foreach
- string[][] combos = new string[arr1.Length * arr2.Length][];
- int ii = 0;
- foreach(var strOne in arr1)
- {
- foreach(var strTwo in arr2)
- {
- string[] combo = new string[2];
- combo[0] = strOne;
- combo[1] = strTwo;
- combos[ii] = combo;
- ii++;
- }
- }
- return combos;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement