Mel Pama
Mel Pama

Reputation: 1429

Using different comparison operators based on conditional logic

I don't want to duplicate tons of code in my Application so I would like to do the following.

// PSEUDO CODE

if (next == true) {operator = "<=";}
else {operator = ">=";}

// Should use "row >= nowRow" or "row <= nowRow" to avoid having repeated code
if (row.Count operator nowRow) { ... }

Any suggestions?

Upvotes: 1

Views: 81

Answers (2)

Keith Nicholas
Keith Nicholas

Reputation: 44298

you can use lambda expressions to do something like

var compare = next ? (Func<int,int,bool>)((l, r) => l <= r) : ((l, r) => l >= r);

if(compare(rowDat.Count, nowRow))
{
}

Upvotes: 1

Lesiak
Lesiak

Reputation: 26006

You can assign a function to a variable of a delegate type. In your case, Func<T1,T2,TResult> Delegate is appropriate.

Func<int, int, bool> func = (x,y) => x <= y;
Console.WriteLine(func(1,2));

Upvotes: 0

Related Questions