How to do optional parameters in LINQ?
Here is what I'm trying to do:
(Dc.DET_Cases.Where(c => c.ProductID == pl.ProductID
&& oldTOR == false ? c.OldTOR == oldTOR :
&& (productLineName.ToInt() == 0 || productLineName.ToInt() == c.ProductLineID)
&& (productCategory.ToInt() == 0 || productCategory.ToInt() == c.ProductCategoryID)
&& (issueType.ToInt() == 0 || issueType.ToInt() == c.IssueTypeID)
&& (issue.ToInt() == 0 || issue.ToInt() ==开发者_运维问答 c.IssueID)
)
.FirstOrDefault() != null)
This is the line I'm trying to do.
oldTOR == false ? c.OldTOR == oldTOR :
inside a where
LINQ statement. If the value is false then compare the value. If not, then ignore it.
The easiest way to do this is to just set the other option to be true
.
Ie: !oldTOR ? c.OldTOR == oldTOR : true
This means that if oldTor
is false, then we want to compare OldTor's, otherwise, keep evaluating the rest of the expression.
As an aside, I would split each part of your massive .Where()
boolean comparison into individual .Where()
statements. This will improve readability and comprehension of your Linq.
Dc.DET_Cases
.Where(c => c.ProductID == pl.ProductID)
.Where(c => !oldTOR ? c.OldTOR == oldTOR : true)
.Where(c => productLineName.ToInt() == 0 || productLineName.ToInt() == c.ProductLineID)
.Where(c => productCategory.ToInt() == 0 || productCategory.ToInt() == c.ProductCategoryID)
.Where(c => issueType.ToInt() == 0 || issueType.ToInt() == c.IssueTypeID)
.Where(c => issue.ToInt() == 0 || issue.ToInt() == c.IssueID)
.FirstOrDefault() != null;
This makes it clear that if oldTor
is false
then you want to compare, otherwise, pass that statement (true
).
I think you can use the LINQ Dynamic Query Library.
And then create a query as you like.
The fastest way to do this is by evaluation paths:
oldTOR && (c.OldTor == oldTOR)
Why is this the fastest? Answer: if oldTOR
is false then the whole and statement is false, and there is no need to compare the rest of the statement.
精彩评论