C# Lambda 表达式“IN”运算符是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13507827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lambda expression "IN" operator Exists?
提问by sivaL
I'm looking for to build the Lambda expression like the below
我正在寻找构建如下所示的 Lambda 表达式
IQueryable<Object> queryEntity =
_db.Projects.Where(Project=>Project.Id.IN(1,2,3,4));
I don't find any INoperator in Lambda expression.
我IN在 Lambda 表达式中找不到任何运算符。
Anybody have suggestions?
有人有建议吗?
采纳答案by Anders Arpi
Use IEnumerable.Containsfor this.
为此使用IEnumerable.Contains。
var idList = new[] { 1, 2, 3, 4 };
IQueryable<Object> queryEntity =
_db.Projects.Where(Project => idList.Contains(Project.Id));
You could construct the idListinline of course.
您idList当然可以构建内联。
回答by Tilak
You are looking for IEnumerable.Contains
您正在寻找IEnumerable.Contains
_db.Projects.Where(Project => list.Contains(Project.Id));
回答by joshjeppson
There is no in operator, but there is a contains. Just invert your logic:
没有 in 运算符,但有一个 contains。只需反转您的逻辑:
IQueryable<Object> queryEntity = _db.Projects.Where(Project=>(new []{1,2,3,4}).Contains(Project.Id));
IQueryable<Object> queryEntity = _db.Projects.Where(Project=>(new []{1,2,3,4}).Contains(Project.Id));
回答by slawekwin
you could write your own
你可以自己写
public static bool In(this object item, IEnumerable list)
{
return list.Contains(item);
}
public static bool In(this object item, params object[] list)
{
return item.In(list);
}
回答by Gregory Bologna
pseudocodebased on Andersupvoted solution.
- Assumptions: Uses information from Wikipedia's Historical United States mints.
- Dataset: StateMints.
- Fields: Location, Mint.
- Requirement: select all coins having mint id.
StateMints sample data:
Mint, Location1.O, New Orleans, Louisiana
2.W, West Point, New York
3.D, Denver, Colorado
- 假设:使用来自维基百科美国历史铸币厂的信息。
- 数据集:StateMints。
- 字段:位置,薄荷。
- 要求:选择所有具有 mint id 的硬币。
StateMints 样本数据:
Mint、Location1.O,路易斯安那州新奥尔良
2.W,纽约西点军校 3.D
,科罗拉多州丹佛
This is my code so far:
到目前为止,这是我的代码:
List<string> mints = new List<string> { "C", "CC", "D", "M", "O", "P", "S", "W" };
var locations = StateMints.Where(p => mints.Contains(p.Mint.ToUpper())).Select(p => p.Location).ToList();

