我需要n个字段的组合,其中每个字段可以等于null或null。对于每个组合,都不能重复字段。基本上,应该有2^n的组合。
示例:
如果我有两个字段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我不知道这个组合的名称是什么,那么如何在字段数是一个变量的代码中这样做呢?
谢谢!
发布于 2016-03-02 11:04:05
如果您想要这样的行生成器,可以使用Linq。
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));https://stackoverflow.com/questions/35745040
复制相似问题