Skip to content

Instantly share code, notes, and snippets.

@KevinJones
Created February 13, 2014 19:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinJones/8982149 to your computer and use it in GitHub Desktop.
Save KevinJones/8982149 to your computer and use it in GitHub Desktop.
C# SelectMany Example - Cartesian Product
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