如何在LINQ中执行可选参数?

How*_*ish -2 c# linq

这是我正在尝试做的事情:

(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)
Run Code Online (Sandbox Code Playgroud)

这是我想要做的路线.

oldTOR == false ? c.OldTOR == oldTOR :
Run Code Online (Sandbox Code Playgroud)

whereLINQ语句中.如果值为false,则比较该值.如果没有,那么忽略它.

Ala*_*tts 5

最简单的方法是将另一个选项设置为true.

即: !oldTOR ? c.OldTOR == oldTOR : true

这意味着如果oldTor为false,那么我们想要比较OldTor,否则,继续评估表达式的其余部分.

顺便说一句,我会将你的大量.Where()布尔比较的每个部分分成单独的.Where()语句.这将提高您的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;
Run Code Online (Sandbox Code Playgroud)

这清楚表明,如果oldTor是,false那么你想比较,否则,传递该语句(true).