在LINQ中if else条件

时间:2013-04-12 14:15:44

标签: c# linq linq-to-sql

我正在学习linq to sql的过程。

是否可以在linq中将以下条件写入sql?

条件1

var query1 = 
             if
             from q in db.Students
             q.fees =="paid" && q.activites == "good" && count == 0
             select q 

              save "OK" to the property result. 

          else 
             from q in db.Students
             q.fees =="paid" && q.activites == "good" && count == 2
             select q 
             save "better" to the property result. 

            else
            from q in db.Students
            q.fees =="paid" && q.activites == "good" && count > 2
            select q 
            save "bad" to the property result. 


  private string _result; 
  public string Result
    {
        get { return this._result; ; }
        set { this._result;  = value; }
    }
亲切的指导。

更新了编辑:

   var query1 =                  
             (from q in db.Students
             q.fees =="paid" && q.activites == "good" 
             select q).Any(); 

  if(count ==0 && query1 == true)
  {
    this.Result = "OK"
  }
  esle if(count == 2  && query1 == true)
  {
    this.Result = "better"
  }
  esle 
  {
    this.Result = "bad"
  }
这会是一种方法吗?

2 个答案:

答案 0 :(得分:1)

由于这都是代码端,因此您可以在运行LINQ查询后使用常规的if-else模式。

示例:

var query1 =                  
         from q in db.Students
         q.fees =="paid" && q.activites == "good" 
         select q;

if(count ==0 && query1.Count() > 0)
{
    this.Result = "OK";
}
else if(count == 2  && query1.Count() > 0)
{
    this.Result = "better";
}
else 
{
    this.Result = "bad";
}     

由于LINQ仅用于确定记录是否存在,我建议使用.Any()方法。

var recordsFound = db.Students.Any(q => q.fees =="paid" && q.activites == "good");

if(count == 0 && recordsFound)
{
    this.Result = "OK";
}
else if(count == 2 && recordsFound)
{
    this.Result = "better";
}
else 
{
    this.Result = "bad";
}

答案 1 :(得分:0)

看起来你总是在相同的条件下查询,你唯一有条件的做法就是返回的结果数量。您可以使用where条件获取结果,然后在结果计数周围添加if语句。

var count = (from q in db.Students
where q.fees == "paid" && q.activities == "good"
select q).Count();

if(count == 0){
     //do something
 }
 else if(count == 2){
     //do something 
 }
 ///etc...