LINQ - 条件 - " if-else"案例

时间:2016-03-15 07:32:06

标签: c# linq linq-to-sql

我有以下Linq查询。我想要的是如果我搜索特定的year,我应该得到year的相应记录。其他只是显示当年的记录。同样的方式searchtext也必须完成。

    public ActionResult Search(string searchtext, int? year)
    {
                string selyear = year.ToString();
                string curyear = (DateTime.Now.Year).ToString();

                hdms = from t in db.HOLIDAY                           
                       where    
                           (year == null || t.DOH.StartsWith(selyear)) &&
                           (searchtext == "" || t.HOLIDAY_NAME == searchtext)                      
                       select new HOLIDAYDETAILS
                       {
                           DOH = t.DOH,                               
                       };
                       ....
    }

我也想满足这个if (year == null) then t.DOH.StartsWith(curyear)

if (searchtext == "") then t.HOLIDAY_NAME != "Sunday" && t.HOLIDAY_NAME != "Saturday"

如果两者同时为空,则应同时满足两个条件。

我怎么能在上面的where子句中给出这个呢?

2 个答案:

答案 0 :(得分:3)

如果检查年份是否为空是您的问题,那么您可以这样做 -

public ActionResult Search(int? year)
    {
                string selyear = year.ToString();
                string queryyear = (string.IsNullOrEmpty(selyear)) // checking for null
                                   ? (DateTime.Now.Year).ToString() // current year
                                   : selyear; // year in query

                hdms = from t in db.HOLIDAY
                       join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE
                       where    
                           t.DOH.StartsWith(queryyear)  // comparing queryyear        

                       orderby
                           t.DOH
                       select new HOLIDAYDETAILS
                       {
                           DOH = t.DOH,                               
                       };
                       ....
    }

希望这对你有用......

答案 1 :(得分:2)

public ActionResult Search(int? year)
{
    string curyear = (DateTime.Now.Year).ToString();
    string selyear = year!=null? year.ToString() : curyear;

    var query = from t in db.HOLIDAY
                join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE
                select new {t,t1};

    query = query.Where(o=>o.t.DOH.StartsWith(selyear));

    if (searchtext == "")
    {
        query = query.Where(o=>o.t.HOLIDAY_NAME != "Sunday" && o.t.HOLIDAY_NAME != "Saturday");
    }

    hdms = query.OrderBy(o=>o.t.DOH).Select(o=> new HOLIDAYDETAILS
           {
               DOH = o.t.DOH,                               
           });
   ....
}