Search code examples
c#variablescomparison

Greater in variable


Is there a way to say a greater sign > into a variable so I can use in say a for..next loop?

I have the following:

public int findUnused(bool useHighestFirst = true)
{        
    int plInd = 1;
    int stepSize = 1;
    int maxe = maxPlayerCount + 1;
    for (; plInd > maxe; plInd += stepSize)
    {
    // do something
    }
}

Depending on useHighestFirst the for loop has to count UP or DOWN.

How can I put the operator ( < or > ) into a variable?


Solution

  • You can use a Func<int, int, bool>, which represents a function that takes 2 int parameters and returns a bool:

    Func<int, int, bool> condition = (x, y) => x > y;
    // or
    Func<int, int, bool> condition = (x, y) => x < y;
    

    And then you can do:

    for (; condition(plInd, maxe); plInd += stepSize)