C# 使用 LINQ 从数组中查询 Int Id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11030522/
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-09 16:11:50  来源:igfitidea点击:

Using LINQ To Query Int Ids From An Array

c#linq

提问by GrahamJRoy

I have an array of Ids that I want to pass to the entity framework via a Linq query to return any matches

我有一个 Id 数组,我想通过 Linq 查询传递给实体框架以返回任何匹配项

I have written Linq queries that can convert Ids to strings and use the 'Contains' operator, such as:

我编写了可以将 Id 转换为字符串并使用“包含”运算符的 Linq 查询,例如:

Model

模型

public class Order {
  public long OrderId { get; set; }
  public string Name { get; set; } ...}

Order[] orders = { new Order { OrderId = 123, Name = "Order1" }, new Order {...},...};

for which I can use something like:

我可以使用类似的东西:

long[] testArray = {123, 456};

and then

进而

var result = orders.Where(i => testArray.ToString().Contains(i.OrderId.ToString()));

but do I really need to keep casting the Ids to strings? It looks as though I can't access the 'Contains' if I keep them as ints.

但是我真的需要继续将 Id 转换为字符串吗?如果我将它们保留为整数,看起来好像我无法访问“包含”。

Ultimately, I want to be able to use this as part of a query that accesses the Entity Framework and so passes the query as part of an IQueryable<> to make sure I am not returning reams of data when I only want a handfull, such as:

最终,我希望能够将其用作访问实体框架的查询的一部分,因此将查询作为 IQueryable<> 的一部分传递,以确保当我只需要少量数据时,我不会返回大量数据,例如作为:

var orders = _repo.Orders().Where(i => orderArray.Contains(i.OrderId));

So any solution it would be useful if the query params (the int array) through the EF rather than getting all of the data and then checking it in memory.

因此,如果查询参数(int 数组)通过 EF 而不是获取所有数据然后在内存中检查,那么任何解决方案都会很有用。

Cheers!

干杯!

采纳答案by Jon Skeet

but do I really need to keep casting the Ids to strings

但是我真的需要继续将 Id 转换为字符串吗?

Absolutely not. It's not clear what barsis, but assuming it should really be orders, you could use:

绝对不。目前尚不清楚是什么bars,但假设它真的应该是orders,你可以使用:

var result = orders.Where(i => testArray.Contains(i.OrderId));

or perform a join:

或执行连接:

var result = orders.Join(testArray, o => o.OrderId, id => id, (o, id) => o);

回答by Clueless

you can use the Intersect operator instead, why do you use arrays and not lists? code example:

您可以改用 Intersect 运算符,为什么使用数组而不是列表?代码示例:

      public class Order {
  public long OrderId { get; set; }
  public string Name { get; set; }}


    public class Rep
    {
        private List<Order> orders { get; set; }

        public void Q()
        {
            long[] testArray = {123, 456};
            var res  = orders.Intersect(orders);
        }
    }