0

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?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Peter
  • 13
  • 2
  • Yes, but the logic is messy. First add some code at the end of your loop that inverts stepSize if maxe or zero is reached. Then in your loop conditional expression, put some logic in the does the comparison one way for a positive stepSize and the opposite way if it's negative – Flydog57 Jul 27 '18 at 00:05
  • Possible duplicate of [Store an operator in a variable](https://stackoverflow.com/questions/14255618/store-an-operator-in-a-variable) – Nathalia Soragge Jul 27 '18 at 00:10

1 Answers1

2

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)
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    and don't forget to change the sign of `stepSize` for the countdown version. – Cee McSharpface Jul 27 '18 at 00:03
  • @dlatikay I think the OP handled that already. He probably set it to a negative value beforehand. That is not the question so I didn't include it in my answer. OP would have asked about that if they didn't know how to do it. I think OP is just confused as to how to do the condition part. – Sweeper Jul 27 '18 at 00:04
  • Worked like a treat. Thanks – Peter Jul 27 '18 at 00:09