4

I am having

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

I want to generate string from these words such that no string is duplicate and Here duplicate means each and every string must contain unique words

e.g if once generated 'How are you' then 'are you how' should not be considered in result'.

I can have any number of list

e.g

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

These list are going to be added in AllSimilarWordsLists. I want to generate list of string using cartesian products . Have found this but this solution is having fix number of lists, Anybody having ideas.

Community
  • 1
  • 1
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60

1 Answers1

9

Unfortunately 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;
}
Vladmir
  • 1,255
  • 9
  • 13
  • Could the source have been http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx - not exactly the same but pretty close. – Chris Sep 03 '14 at 11:45
  • Yes, I think, you are right. Eric Lippert is very trustworthy source to use – Vladmir Sep 03 '14 at 12:57
  • Can you provide the input parameters and outcome so I could help you? Thanks – Vladmir Apr 18 '16 at 15:41
  • @Vladmir can u add input and output to show how we should use it? thanks – pmn Feb 18 '18 at 07:11
  • 2
    Here's an updated link to Eric Lippert's article: https://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ – Enigmativity Nov 02 '21 at 09:00