C# LINQ combinatorics: All Combinations of a Set without the Empty Set

后端 未结 1 1353
甜味超标
甜味超标 2020-12-18 01:50

I have a set of strings, and I want to find all possible combinations of the strings and add them to a list. I want to end up with a list of a list of each combination of th

相关标签:
1条回答
  • 2020-12-18 02:21

    Providing that all the values in the list are 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 out:

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

    The outcome is

    a
    b
    a, b
    c
    a, c
    b, c
    a, b, c
    
    0 讨论(0)
提交回复
热议问题