Reputation: 3
The goal is to have some code to build filtering condition for Where
call.
In FoxPro I'd use condition built as string ("foo == 3 && bar > 5"
) and execute it later.
I am trying similar approach in C# - create string and use it as condition in the code below but can't find way to do it:
string Condition = "";
...
if (xyz > 0)
Condition = "scr.ZipCode = 12345";
if (xyz > 1)
Condition = "scr.ZipCode = 23456";
if (xyz > 2)
Condition = "scr.ZipCode = 34567";
...etc.
and then use it in the code:
var shippingShipCalculatorRecords =
_shippingShipCalculatorService.GetAllShippingShipCalculatorRecords()
.Where(scr => (
(scr.CountryId == 0 && Condition)
)
.OrderBy(x => x.Sequence).ToList();
I've tried to convert it to bool but it didn't work neither. I use to work in FoxPro and could easily achieve it (&Condition).
Upvotes: 0
Views: 135
Reputation: 9201
Sorry, but AFAIK I'm afraid you can't do that. However, you can hold on the zip code in a variable and use it later in your condition :
string zipcode = string.Empty; //Or an int, if it is stored like so
if (xyz > 0)
zipcode = "12345";
if (xyz > 1)
zipcode = "23456";
if (xyz > 2)
zipcode = "34567";
So your condition will now be
(scr.CountryId == 0 && src.ZipCode == zipcode)
Upvotes: 2
Reputation: 203835
Rather than making your condition a string, have it be an Expression<Func<YourEntityType, bool>>
so that you can still have compile time verification that your syntax is all valid:
Expression<Func<YourEntityType, bool>> Condition;
if (xyz > 0)
Condition = scr => scr.ZipCode == 12345;
else if (xyz > 1)
Condition = scr => scr.ZipCode == 23456;
else if (xyz > 2)
Condition = scr => scr.SomeOtherField == "someStringValue";
else
Condition = scr => true; //or whatever makes sense as a default choice
var shippingShipCalculatorRecords =
_shippingShipCalculatorService.GetAllShippingShipCalculatorRecords()
.Where(scr => scr.CountryId == 0)
.Where(Condition)
.OrderBy(x => x.Sequence).ToList();
Upvotes: 7