这两种扩展方法将让您将多个枚举链接在一起,计算您想要的组合。
每个组合都是一个枚举,而不是一个串联的字符串。
// 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.
// e.g. { 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.
// e.g. { { 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" }, ...
或者,有这篇经典的 Eric Lippert博客文章也做了类似的事情。(类似的结果,非常不同的方法。)