Reputation: 970
I am trying to use ternary operator in a linq query like below
ordersupplierinvoiceSort = ordersupplierinvoiceSort
.Where(a => a.OrderSupplierInvoiceVATs.Any(b => b.VATPercentage = from.Value.Year < 2017 ? 8 : 10 && b.DeletedOn == null && b.DeletedByUserId == null && b.OrderSupplierInvoice.TransactionTypeId == 1));
But i am getting this error
operator '&&' cannot be applied to operands of type 'int' and 'bool'
Help appreciated. Thanks!
Upvotes: 0
Views: 5015
Reputation: 460108
First, you need ==
instead of =
if you want to compare two values.
I guess from
is a local variable, then you can calculate the percentage also before the query:
int percentage = from.Value.Year < 2017 ? 8 : 10;
ordersupplierinvoiceSort = ordersupplierinvoiceSort
.Where(a => a.OrderSupplierInvoiceVATs
.Any(b => b.VATPercentage == percentage
&& b.DeletedOn == null
&& b.DeletedByUserId == null
&& b.OrderSupplierInvoice.TransactionTypeId == 1));
This improves readability and works. Otherwise you need to wrap it within parentheses because of the rules of operator precedences.
Upvotes: 3
Reputation: 43886
Your problem is operator precedence. The &&
operator has higher priority than the ternary operator, so use parenthesis:
ordersupplierinvoiceSort = ordersupplierinvoiceSort
.Where(a => a.OrderSupplierInvoiceVATs
.Any(b => b.VATPercentage == (from.Value.Year < 2017 ? 8 : 10) &&
b.DeletedOn == null &&
b.DeletedByUserId == null &&
b.OrderSupplierInvoice.TransactionTypeId == 1));
Plus you miss a =
at b.VATPercentage == (from...
.
Upvotes: 2