所以我有一个需要字符串的方法。该字符串由一个常量值和 2 个布尔值、2 个常量整数和一个可以是 10,20 或 30 的整数组成。这都是一个字符串,其中参数由下划线分隔。
Example:
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(string Combination) 方法运行它们?
您可以使用非常易读的 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();
}
编辑:请记住,必须在上述解决方案中创建多个数组,因为子句被评估多次 https://stackoverflow.com/questions/34975128/how-often-is-the-in-clause-evaluated-in-a-linq-query。您可以将其更改为以下内容来规避此问题:
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)