在三元组中返回“NOT NULL”,我需要说== NOT NULL?

时间:2015-02-05 15:48:41

标签: c# lambda entity-framework-4

鉴于此代码:

            dataSource = this.db.DailyProductionReportSummaries.Where(
                x => x.ShiftDate >= start && x.ShiftDate <= end &&
                x.Shift == (shift != null ? shift.Code : "SOMETHING ELSE") &&  //TODO: "SOMETHING ELSE" where it's not null
                x.LineNumber == (shift != null ? lineNumber : 0) && //TODO: 0 where it's not null
                x.ProductCode == (productNumber != 0 ? productNumber.ToString() : "SOMETHING ELSE") //TODO: "SOMETHING ELSE" where it's not null
                ).ToList();

我需要在每个标有“TODO”的三元组中说明(特别针对//TODO的第一行:

  

如果shift中包含某些内容,请返回shift.Code,否则返回评估为x.Shift == NOT NULL的“Something”(或更明确地评估为x.shift != null

我是在这里坚持一个愿望还是我需要继续将其扩展为一堆if陈述? (我试图将多个if语句压缩成更紧凑的东西,适应更改配置而不需要进行大量的逻辑更改或重写......

1 个答案:

答案 0 :(得分:4)

最易读的替代 将其扩展为一堆if语句。请注意,您不需要拼出每个替代方案,也不需要一堆if嵌套,您可以通过反复调用Where来简单地链接过滤器。

var query = this.db.DailyProductionReportSummaries.AsQueryable();

query = query.Where(x => x.ShiftDate >= start && x.ShiftDate <= end);

if (shift == null)
    query = query.Where(x => x.Shift != null
                          && x.LineNumber != null);
else
    query = query.Where(x => x.Shift == shift.Code
                          && x.LineNumber == lineNumber);

if (productNumber == 0)
    query = query.Where(x => x.ProductCode != null);
else
    query = query.Where(x => x.ProductCode == productNumber.ToString());

dataSource = query.ToList();