使用LINQ从数组查询整数ID [英] Using LINQ To Query Int Ids From An Array

查看:38
本文介绍了使用LINQ从数组查询整数ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID数组,希望通过Linq查询传递给实体框架以返回所有匹配项

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

我编写了Linq查询,该查询可以将IDs转换为字符串并使用'Contains'运算符,例如:

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

型号

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

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

我可以使用类似的东西

long[] testArray = {123, 456};

然后

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

但是我真的需要继续将Id强制转换为字符串吗?如果将它们保留为整数,则好像无法访问包含".

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.

最终,我希望能够将其用作访问实体框架的查询的一部分,并因此将查询作为IQueryable的一部分传递. handfull,例如:

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:

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

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

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.

干杯!

推荐答案

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

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

绝对不是.目前尚不清楚bars是什么,但是假设它确实应该是orders,则可以使用:

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

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

或执行加入:

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

这篇关于使用LINQ从数组查询整数ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆