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

最后都变了- 提交于 2019-11-29 07:06:26

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!