[英]Can one use “in” type statements in C# and LINQ Lambda expressions?
I need from time to time to compare a number of values like: 我需要不时比较一些值,例如:
if (myCurrentUser.Role in ("Admin","User"))
But it seems the above may not be possible, and instead one needs to do: 但是,似乎以上方法不可能实现,而需要这样做:
if (myCurrentUser.Role == "Admin" || myCurrentUser.Role == "User")
Which starts to gets quite long. 这开始变得很长。
So is there a way to have an "in" approach. 因此,有一种方法可以采用“介入”方法。 Obviously one can do this in SQL.
显然,可以在SQL中做到这一点。
Also I would like to use this in LINQ Lambda expressions as well. 我也想在LINQ Lambda表达式中使用它。
var myRecords = db.mytable.where(r=>r.name in ("Roy","Jack"))
currently I write this as: 目前我写为:
var myRecords = db.mytable.where(r=>((r.name == "Roy")||(r.name == "Jack")));
Thanks in advance. 提前致谢。
You can do it with Contains
. 您可以使用
Contains
做到这一点。 Try this: 尝试这个:
var names = new List<string>() { "Roy", "Jack" };
db.mytable.Where(r => names.Contains(r.name));
尝试使用contains,例如:
var x = (new string[] {"A", "B"}).Contains("C");
If you add this extension method: 如果添加此扩展方法:
public static class Extensions
{
public static bool IsIn<T>(this T source, params T[] values)
{
return values.Contains(source);
}
}
You can write code like this: 您可以编写如下代码:
if (myCurrentUser.Role.IsIn("Admin","User"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.