C#创建所有可能的组合的字符串 [英] C# Create strings with all possible combinations
问题描述
所以我有一个接受一个字符串的方法。该字符串是从一个恒定值和2的bool,2常整型,和int,可以是10,20或30这都将是其中的参数用下划线分隔字符串建立起来了。
So I have a method which takes a string. The string is built up from a constant value and 2 bools, 2 constant ints, and an int that can be 10,20 or 30. this will all be a string where the parameters are seperated by underscore.
例如:
string value = "horse"
string combination1 = value+"_true_false_1_1_20";
dostuff(combination1);
我需要通过
I need to run every single possible combination through
我要如何利用这个恒定值,并通过该方法运行它与所有可能的组合
How do I take this constant value and run it through the method with all of the possible combinations ?
字符串建:VALUE_BOOL1_BOOL2_CONSTINT1_CONSTINT2_INT1
String built: "VALUE_BOOL1_BOOL2_CONSTINT1_CONSTINT2_INT1"
Possibilities
VALUE = Horse
BOOL1 = True, False
BOOL2 = True, False
CONSTINT1 = 1
CONSTINT2 = 1,
INT1 = 10, 20, 30
如何我可以把预定义的字符串值,并创造一切可能的组合,并通过doStuff(字符串组合)方式运行呢?
How can I take the predefined value string and create all possible combinations and run them through the doStuff(string combination) method ?
推荐答案
您可以用一个非常可读的LINQ语句来做到这一点没有使用循环:
You can do this with a very readable LINQ statement without the use of loops:
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();
}
编辑:记住该多个阵列已经在上述溶液中创建,因为中子句被评为多次的。你可以将其更改为以下来规避这样的:
Keep in mind that multiple arrays have to be created in the above solution because the in-clause is evaluated multiple times. You could change it to the following to circumvent this:
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();
}
这篇关于C#创建所有可能的组合的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!