I have a set of strings and I want to find all possible combinations of strings and add them to the list. I want to finish the list list of each string combination, minus the empty set.
I created a solution that does this with a nested loop. However, I want to do it more elegantly, preferably with LINQ , and I'm not so good at it, because I'm still pretty new to it.
The solution should have 2 ^ n - 1 combinations, where n is the power of the original set. Here is the right example of what I'm looking for:
set = {a, b, c} completedListOfCombinations = { {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c} }
Here is my working, basic, but ugly solution, which I created with: https://stackoverflow.com/a/364628/
List<string> myStrings = new List<string> { "a", "b", "c" }; var allCombos = new List<List<string>>(); for (int i = 0; i < myStrings.Count; i++) { int subsetCount = allCombos.Count; var m = new List<string>(); m.Add(myStrings[i]); allCombos.Add(m); for (int j = 0; j < subsetCount; j++) { string[] subset = new string[allCombos.ElementAt(j).Count + 1]; allCombos[j].CopyTo(subset, 0); subset[subset.Length - 1] = myStrings[i]; allCombos.Add(subset.ToList()); } }
Can someone show me a more elegant solution for this? I saw similar LINQ solutions that create Cartesian pairs and threshold lists, but I could not configure them for me to need.