在Linq查询中使用条件if语句

时间:2014-08-29 18:20:41

标签: c# linq

我试图编写一个使用if语句的linq查询。

在下面的代码中,我正在搜索

的匹配项

n.SAU_ID = sau.SAUID where

ReportingPeriod列包含" Oct1"然后  FiscalYear - aprYearDiff = sau.SAUYearCode。

否则

FiscalYear - octYearDiff = sau.SAUYearCode。

我的代码只为SAUID和" Oct1"提供匹配。

实施theese声明需要哪些代码?

    int FiscalYear = 2014;       

    List<String> addtowns = new List<string>();

    List<Stage_Reorg> reorg = _entities.Stage_Reorg.ToList();

    int aprYearDiff = 2;
    int octYearDiff = 1;

    foreach (var sau in reorg)
    {
        addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
        .Where(n => n.SAU_ID == sau.SAUID 
            && (n.ReportingPeriod == "Oct1" 
            ? (FiscalYear - aprYearDiff) == sau.SAUYearCode 
            : (FiscalYear - octYearDiff) == sau.SAUYearCode))
        .Select(n =>  n.TownCode ));
    }

2 个答案:

答案 0 :(得分:1)

这是一种可行的方法,但这可能不适用于EF。您需要将所有记录加载到内存中然后执行过滤:

addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
    .Where(n => { 
                   bool b = n.ReportingPeriod == "Oct1" 
                           ? (FiscalYear - aprYearDiff) == sau.SAUYearCode 
                           : (FiscalYear - octYearDiff) == sau.SAUYearCode);
                  return b && n.SAU_ID == sau.SAUID;
                 }).Select(n =>  n.TownCode ))

答案 1 :(得分:1)

无论如何,这是一个坏主意。将条件转换为

(n.ReportingPeriod == "Oct1" && (FiscalYear - aprYearDiff) == sau.SAUYearCode)  
|| (n.ReportingPeriod != "Oct1" && (FiscalYear - octYearDiff) == sau.SAUYearCode)