These two extension methods allow you to combine several enumerations, calculating the combinations you want.
Each combination is an enumeration, not a concatenated string.
// This method takes two sequences of T, and returns // - each element of the first sequence, // wrapped in its own one-element sequence // - each element of the second sequence, // wrapped in its own one-element sequence // - each pair of elements (one from each sequence), // as a two-element sequence. // eg { 1 }.CrossWith({ 2 }) returns { { 1 }, { 2 }, { 1, 2 } } public static IEnumerable<IEnumerable<T>> CrossWith<T>( this IEnumerable<T> source1, IEnumerable<T> source2) { foreach(T s1 in source1) yield return new[] { s1 }; foreach(T s2 in source2) yield return new[] { s2 }; foreach(T s1 in source1) foreach(T s2 in source2) yield return new[] { s1, s2 }; } // This method takes a sequence of sequences of T and a sequence of T, // and returns // - each sequence from the first sequence // - each element of the second sequence, // wrapped in its own one-element sequence // - each pair, with the element from the second sequence appended to the // sequence from the first sequence. // eg { { 1, 2 } }.CrossWith({ 3 }) returns // { { 1, 2 }, { 3 }, { 1, 2, 3 } } public static IEnumerable<IEnumerable<T>> CrossWith<T>( this IEnumerable<IEnumerable<T>> source1, IEnumerable<T> source2) { foreach(IEnumerable<T> s1 in source1) yield return s1; foreach(T s2 in source2) yield return new[] { s2 }; foreach(IEnumerable<T> s1 in source1) foreach(T s2 in source2) yield return s1.Concat(new[] { s2 }).ToArray(); } var cross = lBag1.CrossWith(lBag2).CrossWith(lBag3); // { "1_0" }, { "1_1" }, { "1_3" } ... // ... { "1_0", "11_0" }, ...
Also, there is this classic Eric Lippert post that does a similar thing. (A similar result, a very different method.)
Rawling
source share