如果在C#中使用LINQ中的多个条件

时间:2015-04-09 06:25:59

标签: c# linq

我有linq查询,我需要设置条件p.conditionVariable > 0我将应用以下条件。

from prob in table2.where(p => p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive)

如果p.conditionVariable == 0,则以下内容保持不变。

(from _obj1 in table1.Where(p => p.IsActive == true))
                           from prob in table2.Where(p => p.Id == _obj1.Id && !p.IsBlocked && p.IsActive && p.ConditionVariable == 0)
                           select new Class1
                           {
                               Title = prob.Title,
                               Status = prob.IsPending,
                               Id = obj1.id 
                           }

2 个答案:

答案 0 :(得分:1)

我认为您希望在条件之间设置||table2将根据p.CondtionVariable查询。{/ p>

(from _obj1 in table1.Where(p => p.IsActive == true))
   from prob in table2.Where(p => (p.Id == _obj1.Id && !p.IsBlocked && p.IsActive && p.ConditionVariable == 0)
                               || (p.ConditionVariable > 0 && p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive))
   select new Class1
   {
       Title = prob.Title,
       Status = prob.IsPending,
       Id = _obj1.id 
   }

如果您想使用if/else条件,可以使用类似

的内容
(from _obj1 in table1.Where(p => p.IsActive == true))
   from prob in table2.Where(p => {
            bool state = false;
            if(p.ConditionVariable > 0)  {
                state = p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive;
            } else if(p.ConditionVariable == 0) {
                state = p.Id == _obj1.Id && !p.IsBlocked && p.IsActive;
            }
            return state;   
        })
   select new Class1
   {
       Title = prob.Title,
       Status = prob.IsPending,
       Id = _obj1.id 
   }

答案 1 :(得分:0)

我会把p.ConditionVariable测试放在开头,所以这是检查的第一件事(因为&&操作在第一个失败的情况下停止。如果第一次检查失败,那么接下来检查||操作) :

(from _obj1 in table1.Where(p => p.IsActive == true))
                           from prob in table2.Where(
                               (p => p.ConditionVariable == 0 && p.Id == _obj1.Id && !p.IsBlocked && p.IsActive) 
                               || (p.ConditionVariable > 0 && p.Id == p.ConditionVariable && !p.IsBlocked && p.IsActive))
                           select new Class1
                           {
                               Title = prob.Title,
                               Status = prob.IsPending,
                               Id = obj1.id 
                           }

myvariable = 0也可能有第二种变体吗? ....正如有人评论,但在这种情况下,你没有必要,因为你有|| &安培;&安培;无论如何,那里的运营商。