C#LINQ combinatorics:不包含空集的集合的所有组合 [英] C# LINQ combinatorics: All Combinations of a Set without the Empty Set
问题描述
我有一组字符串,我想找到所有可能的字符串组合并将它们添加到列表中.我想最后得到的是每个字符串组合列表的列表,减去空集.
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 the strings, minus the empty set.
我创建了一个解决方案,该解决方案使用嵌套的for循环来实现此目的.但是我想更优雅地执行此操作,最好使用LINQ ,而且我不太熟练,因为我还很陌生.
I have created a solution that does this exactly with a nested for loop. However I want to do this more elegantly, preferably with LINQ, and I am not so proficient with it because I'm still pretty new to it.
解决方案应具有2 ^ n-1个组合列表,其中n是原始集合的基数.这是我要寻找的正确示例:
The solution should have 2^n - 1 lists of combinations where n is the cardinality of the original set. Here is a correct example of what I am looking for:
set = {a, b, c}
completedListOfCombinations =
{
{a},
{b},
{a, b},
{c},
{a, c},
{b, c},
{a, b, c}
}
这是我在以下帮助下制定的工作,基本但难看的解决方案: https://stackoverflow.com/a/3319652 /3371287
Here is my working, basic but ugly solution that I crafted with help from: https://stackoverflow.com/a/3319652/3371287
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());
}
}
有人可以给我看一个更优雅的解决方案吗?我见过类似的LINQ解决方案,它们创建带有阈值的笛卡尔对和列表,但是我无法根据我的需要对其进行调整.
Can someone show me a more elegant solution for this? I have seen similar LINQ solutions that create Cartesian Pairs and lists with a threshold, but I have not been able to tweak them to what I need.
推荐答案
提供 all 中list
中的值是唯一:
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());
要打印:
Console.WriteLine(String
.Join(Environment.NewLine, result
.Select(line => String.Join(", ", line))));
结果是
a
b
a, b
c
a, c
b, c
a, b, c
这篇关于C#LINQ combinatorics:不包含空集的集合的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!