简体   繁体   English

如何在Linq中使用OR运算符

[英]How to use OR operator in Linq

I want to use OR function in my linq query. 我想在linq查询中使用OR函数。 Ex: Sql: 例如:SQL:

select * from tblusers where userid=1 and status='a' or status='b';

Linq: Linq:

var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");

It's does work for linq query. 它确实适用于linq查询。 so does anyone have any idea? 有人知道吗?

So you are aware about the && operator for comparison, then why not make a try with || 因此,您知道了&&运算符以进行比较,然后为什么不尝试|| operator? 操作员? Anyway here is the solution for your problem, Following code will get you the result with UserID is 1 and status is either a or B . 无论如何,这是解决您问题的方法,以下代码将为您提供UserID为1且状态为aB

 _Repository.selectAll().where(x=>x.UserID==1 && (x.status=="a" || x.status=="B"));

Create an array of status you want to check and then use contains . 创建要检查的状态数组,然后使用contains something like this. 这样的事情。

var statusList = new[] {"a", "b"};

.Where(x=> x.UserID == 1 &&  statusList.Contains(x.status));

Adding my 2 cents in here, there is another way you can write your sql query in C# which more or less resembles the sql syntax. 在这里加2美分,还有另一种方法可以用C#编写sql查询,它或多或少类似于sql语法。

var result = from x in _Repository.SelectAll() where x.UserID == 1 && (x.Status == "a" || x.Status == "B") select x;

This syntax is Query Syntax/Expression where as your snippet is Method Syntax/Expression . 该语法是查询语法/表达式 ,其中您的代码段是方法语法/表达式 Both will achieve same results. 两者将达到相同的结果。 Also behind the scene, query syntax is compiled to Method syntax. 同样在后台,查询语法被编译为方法语法。

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. 在编译时,查询表达式将根据C#规范中列出的规则转换为“标准查询运算符”方法调用。 Any query that can be expressed by using query syntax can also be expressed by using method syntax. 可以使用查询语法表示的任何查询也可以使用方法语法表示。 However, in most cases query syntax is more readable and concise. 但是,在大多数情况下,查询语法更具可读性和简洁性。

Or other approach with List.Contains , which generates sql query like 或其他使用List.Contains方法,它会生成sql查询,例如
SELECT * FROM tblusers WHERE userid=1 AND status IN ('a','b');

var acceptedStatus = new List<string> { 'a', 'b' };
var result= _Repository.selectAll()
                       .Where(x => x.UserID == 1)
                       .Where(x => acceptedStatus.Contains(x.Status));

Notice that instead of && operator you can use another Where function and chain them. 注意,除了&&运算符,还可以使用另一个Where函数并将它们链接起来。 Can be more readable then fit all conditions in one line. 可能更具可读性,然后将所有条件放在一行中。

Try code: 尝试代码:

var result =( from  x in _Repository.selectAll()
           where x.UserID==1 && (x.status=="a" || x.status=="B") select x);

another Solution 另一个解决方案

 var result =( from  x in _Repository.selectAll().where(c=>c.status=="a" || x.status=="B")
               where x.UserID==1  select x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM