3

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 ?

1

1 Answer 1

6

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. Probably you should also keep an eye on my follow-up question which discusses the performance of this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.