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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:48:03  来源:igfitidea点击:

Lambda expression "IN" operator Exists?

c#c#-4.0lambdaentity-framework-5

提问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.

基于Andersupvoted 解决方案的伪代码

  1. Assumptions: Uses information from Wikipedia's Historical United States mints.
  2. Dataset: StateMints.
  3. Fields: Location, Mint.
  4. Requirement: select all coins having mint id.
  5. StateMints sample data:
    Mint, Location

    1.O, New Orleans, Louisiana
    2.W, West Point, New York
    3.D, Denver, Colorado

  1. 假设:使用来自维基百科美国历史铸币厂的信息
  2. 数据集:StateMints。
  3. 字段:位置,薄荷。
  4. 要求:选择所有具有 mint id 的硬币。
  5. StateMints 样本数据:
    Mint、Location

    1.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();