Cartesian products with n number of lists

I have

List<List<string>> AllSimilarWordsLists { get; set; }

I want to generate a line from these words so that not a single line is duplicated, but a duplicate means that each line must contain unique words

For example, if "How are you" is generated once, then "you as" should not be considered as a result. "

I can have any number of lists

eg

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

This list will be added to AllSimilarWordsLists. I want to create a list of strings using Cartesian products. Found this one , but this solution has a fixed number of lists who have ideas.

+3
source share
1 answer

Sorry, I don’t remember where I found it

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;
}
+8

Source: https://habr.com/ru/post/1608245/


All Articles