In the following GetByExpression
, sometimes the r.branchid
is null
. How do I add a conditional in there so it utilises a different field (r.Invoice.Branch.Id
) to check against when r.branchid
is null
?
var t = receiptRepo
.GetByExpression(r => r.BranchId == branchId)
.Where(r => r.Date == selectedDate && r.BatchId == null)
.ToList();
CodePudding user response:
Use a ternary operation
(r.BranchId != null? r.BranchId:r.Invoice.Branch.Id ) == branchId //or whatever you want to compare
CodePudding user response:
You can try using null-coalescing operator ??
:
r => (r.BranchId ?? r.Invoice.BranchId) == branchId
Here if r.BranchId
is null
we use r.Invoice.BranchId
to compare with branchId
. Note, that we can chain ??
operators, e.g.
r => (r.BranchId ?? r.Invoice.BranchId ?? r.Bill.BranchId) == branchId
we try BranchId
if it's null
, we have a look at r.Invoice.BranchId
and if it's null
we get r.Bill.BranchId
etc.
Your Linq query can be
var t = receiptRepo
.GetByExpression(r => (r.BranchId ?? r.Invoice.BranchId) == branchId)
.Where(r => r.Date == selectedDate && r.BatchId == null)
.ToList();
CodePudding user response:
You can do this:
var t = receiptRepo
.GetByExpression(r => (r?.BranchId ?? r.Invoice.BranchId) == branchId)
.Where(r => r.Date == selectedDate && r.BatchId == null)
.ToList();