ここでのEricLippertの投稿は、私が抱えている特定の問題に適していることがわかりました。
問題は、2つ以上のコレクションでそれをどのように使用すべきかについて頭を悩ませることができないことです。
持っている
var collections = new List<List<MyType>>();
foreach(var item in somequery)
{
collections.Add(
new List<MyType> { new MyType { Id = 1} .. n }
);
}
コレクション変数にデカルト積linqクエリを適用するにはどうすればよいですか?
拡張方法は次のとおりです。
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>()};
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] {item})
);
}
2つのコレクションに対するEricの例を次に示します。
var arr1 = new[] {"a", "b", "c"};
var arr2 = new[] { 3, 2, 4 };
var result = from cpLine in CartesianProduct(
from count in arr2 select Enumerable.Range(1, count))
select cpLine.Zip(arr1, (x1, x2) => x2 + x1);