我需要 n 个字段的组合,其中每个字段可以等于 null 或不等于 null。对于每个组合,字段不能重复。基本上,总共应该有 2^n 种组合。
示例:
如果我有 2 个字段 A
和 B
,输出中的组合应该是:
A != null and B != null
A != null and B == null
A == null and B != null
A == null and B == null
如果我有 3 个字段 A、B 和 C,输出中的组合应该是:
A != null and B != null and C != null
A != null and B != null and C == null
A != null and B == null and C != null
A != null and B == null and C == null
A == null and B != null and C != null
A == null and B != null and C == null
A == null and B == null and C != null
A == null and B == null and C == null
我不知道这个组合叫什么,所以我怎么能在字段数是变量的代码中做到这一点?
谢谢!
最佳答案
如果您想要这样的行的
int count = 2;
var lines = Enumerable
.Range(0, 1 << count) // 1 << count == 2 ** count
.Select(item => String.Join(" and ", Enumerable
.Range(0, count)
.Select(index => ((Char) ('A' + index)).ToString() +
((item >> index) % 2 == 0 ? " != null" : " == null"))));
// Let's print out all the lines generated
Console.Write(String.Join(Environment.NewLine, lines));
对于count = 2
,输出是
A != null and B != null
A == null and B != null
A != null and B == null
A == null and B == null
编辑:一个小的修改让您可以输入自己的名字:
String[] names = new String[] { "A", "B", "C" };
var lines = Enumerable
.Range(0, 1 << names.Length) // 1 << count == 2 ** count
.Select(item => String.Join(" and ", Enumerable
.Range(0, names.Length)
.Select(index => names[index] +
((item >> index) % 2 == 0 ? " != null" : " == null"))));
// Let's print out all the lines generated
Console.Write(String.Join(Environment.NewLine, lines));
关于c# - C#中的组合算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745040/