具有n个列表的笛卡尔积

Nit*_*rpe 3 c# linq permutation

我有

List<List<string>> AllSimilarWordsLists { get; set; }
Run Code Online (Sandbox Code Playgroud)

我想从这些单词生成字符串,以便没有字符串重复,这里重复意味着每个字符串必须包含唯一的单词

例如,如果曾经生成'你好吗'那么'你是不是应该在结果中考虑'.

我可以有任意数量的清单

例如

List1   List2   List3   List4   List5
word11  word21  word21  word21  word51
word12  word22  word22  word22  word52
word13  word23  word23  word23  word53
word14  word24  word24  word24  word54
word15  word25  word25  word25  word55
Run Code Online (Sandbox Code Playgroud)

这些列表将添加到AllSimilarWordsLists中.我想使用笛卡尔积生成字符串列表.已经找到了这个,但是这个解决方案有固定数量的列表,任何有想法的人.

小智 9

不幸的是我不记得我在哪里找到它

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>
    (this IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct =
      new[] { Enumerable.Empty<T>() };
    IEnumerable<IEnumerable<T>> result = emptyProduct;
    foreach (IEnumerable<T> sequence in sequences)
    {
        result = from accseq in result from item in sequence select accseq.Concat(new[] {item});
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 以下是 Eric Lippert 文章的更新链接:https://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ (2认同)