简体   繁体   中英

C# Create strings with all possible combinations

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.

Example:

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 ?

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

How can I take the predefined value string and create all possible combinations and run them through the doStuff(string combination) method ?

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();
}

EDIT: 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM