C # LINQ combination: all dialing combinations without empty dialing

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.

+6
source share
1 answer

Provided that all values ​​in list unique:

  List <String> list = new List<String> { "a", "b", "c" }; var result = Enumerable .Range(1, (1 << list.Count) - 1) .Select(index => list.Where((item, idx) => ((1 << idx) & index) != 0).ToList()); 

To print:

 Console.WriteLine(String .Join(Environment.NewLine, result .Select(line => String.Join(", ", line)))); 

Result

 a b a, b c a, c b, c a, b, c 
+11
source

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


All Articles