我需要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));发布于 2016-03-02 11:37:48
在这种情况下,我通常坚持简单的递归,因为它很容易理解。没有任何解释,我只会让(未经测试的)代码本身说话:
public void Generate()
{
Create("", 0);
}
private string[] names = new[]{ "A", "B", "C" };
public void Create(string s, int current)
{
if (current != 0)
{
s += " and ";
}
if (current != names.Length)
{
string c1 = s + names[current] + " == null"; // case 1
string c2 = s + names[current] + " != null"; // case 2
Create(c1, current+1);
Create(c2, current+1);
}
else
{
Console.WriteLine(s);
}
}https://stackoverflow.com/questions/35745040
复制相似问题