使用C#创建包含所有可能组合的字符串

3

我有一个接受字符串的方法。该字符串由常量值、两个布尔值、两个常量整数和一个整数构成,该整数可以是10、20或30。所有参数都将组成一个字符串,以下划线分隔。

例如:

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)方法运行它们?


尝试阅读关于循环的内容:https://msdn.microsoft.com/zh-cn/library/f0e10e56(v=vs.90).aspx - pseudoDust
1个回答

6

你可以使用易于阅读的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();
}

编辑:请注意在上述解决方案中必须创建多个数组,因为in条件在Linq查询中会被多次评估。您可以更改为以下方式来规避这个问题:
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();
}

不用谢。也许你还应该关注一下我的后续问题,它讨论了这种方法的性能。 - Markus Weninger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接