2013-04-12 80 views
0

我正在学习LINQ to sql的过程。如果LINQ中有其他条件

是否有可能在LINQ to 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

http://stackoverflow.com/questions/15909926/linq-if-else-condition/15909991#_=_看到 –

+3

因为这是代码的一面,为什么不使用常规的如 - else模式并将必要的linq查询放入这些块中? – valverij

+0

可以请你举一个例子 – user1221765

回答

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"; 
} 
+0

我会尽力回复,感谢更新@valverij – user1221765

+0

你能解释一下count()> 0在这里是第一个解决方案吗? – user1221765

+0

因为query1的类型是'Enumerable ',所以'.Count()'只返回集合中包含的元素的数量。如果这不是你的意图,那么让我知道,我可以更新答案。 – valverij

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... 
+0

请参阅我的上述评论,我已经尝试过这一点,它与计数工作正常。比较count和query1时我遇到了问题。 – user1221765