Created
February 13, 2014 19:32
-
-
Save KevinJones/8982149 to your computer and use it in GitHub Desktop.
C# SelectMany Example - Cartesian Product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment