C#使用所有可能的组合创建字符串
问题描述:
所以我有一个方法需要一个字符串。该字符串由一个常量值和2个bools,2个常量int以及一个可以为10,20或30的int组成。这将全部是一个字符串,其中参数由下划线分隔。C#使用所有可能的组合创建字符串
例子:
string value = "horse"
string combination1 = value+"_true_false_1_1_20";
dostuff(combination1);
我需要通过
运行每一个可能的组合如何利用这个恒定值,并通过该方法以所有可能的组合的运行呢?
字符串建:“VALUE_BOOL1_BOOL2_CONSTINT1_CONSTINT2_INT1”
Possibilities
VALUE = Horse
BOOL1 = True, False
BOOL2 = True, False
CONSTINT1 = 1
CONSTINT2 = 1,
INT1 = 10, 20, 30
我如何可以采取预先定义的字符串值,并创造一切可能的组合,并通过doStuff(字符串组合)方法运行它们?
答
你可以用一个非常可读的LINQ语句做到这一点,而无需使用循环:
public static List<String> Combis(string value)
{
var combis =
from bool1 in new bool[] {true, false}
from bool2 in new bool[] {true, false}
let i1 = 1
let i2 = 1
from i3 in new int[] {10, 20, 30}
select value + "_" + bool1 + "_" + bool2 + "_" + i1 + "_" + i2 + "_" + i3;
return combis.ToList();
}
编辑:请记住,多个阵列有因为the in-clause is evaluated multiple times上述方案被创建。你可以将其更改为以下来规避这样的:
public static List<String> Combis(string value)
{
bool[] bools = new[] {true, false};
int[] ints = new[] {10, 20, 30};
var combis =
from bool1 in bools
from bool2 in bools
let i1 = 1
let i2 = 1
from i3 in ints
select value + "_" + bool1 + "_" + bool2 + "_" + i1 + "_" + i2 + "_" + i3;
return combis.ToList();
}
+0
别客气。可能你也应该留意我的[后续问题](http://stackoverflow.com/questions/34975128/how-often-is-the-in-clause-evaluated-in-a-linq-query)其中讨论了这种方法的性能。 –
尝试阅读有关循环:https://msdn.microsoft.com/en-us/library/f0e10e56%28v=vs.90%29.aspx – pseudoDust