0

我正在学习 linq to sql。

是否可以在 linq to sql 中编写以下条件?

条件一

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"
  }

这将是一种方法吗?

4

2 回答 2

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";
}
于 2013-04-12T15:03:27.717 回答
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...
于 2013-04-12T14:59:45.100 回答