如何做Linq:“select * from Employee where ID in(10,11,12)” [英] How to do in Linq: "select * from Employee where ID in (10,11,12)"
问题描述
亲爱的Linq,有没有更优雅的方式在Linq中执行此查询?
假设我有一个我感兴趣的ID数组,
int [] employeesToSelect = {10, 11,12};
一个天真的尝试,它编译:
来自e.db.employees中的e,其中e.ID == 10 || e.ID == 11 || e.ID == 12
选择e;
我无法获得更复杂的编译方法,例如:
var q2 =来自db.Employees中的e
其中Array.IndexOf< int>(employeesToSelect,e)
选择e;
这是一个化身已经出现的一个问题。您可以查看以下主题:
- http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID = 731496& SiteID = 1
- http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=582495&SiteID= 1
我尝试通过编写库来解决类似问题(对于字符串关键字),这样可以编写如下代码:
//选择产品,从名称中的数组中获取其中一个值
var q1 = p db 。产品ts 。 ToExpandable()
其中 p 。 ProductName 。 ContainsAny(" Sir" ," Chef" )
选择 新 {p 。 ProductName};
我认为修改它以允许搜索任何类型的数组并不困难。你可以在这里找到它: http://tomasp.net/blog/linq-expand-update.aspx 。
Dear Linq,
is there a more elegant way in Linq to perform this query?
Let's say I have an array of ID's that I am interested in,
int[] employeesToSelect = {10,11,12};
A naive attempt, which does compile:
from e in db.Employees
where e.ID==10 || e.ID==11 || e.ID==12
select e;
I can't get more sophisticated approaches to compile, for example:
var q2 = from e in db.Employees
where Array.IndexOf<int>(employeesToSelect , e)
select e;
Hi, this is an incarnation of one problem that already appeared here. You can look at the following threads:
- http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=731496&SiteID=1
- http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=582495&SiteID=1
I tried to solve similar problem (for string keywords) by writing library that enables you to write code like this:
// Select products, that conain one of values from array in their name
var q1 = from p in db.Products.ToExpandable()
where p.ProductName.ContainsAny("Sir", "Chef")
select new { p.ProductName };I think it wouldn't be difficult to modify it to allow searching in array of any type. You can find it here: http://tomasp.net/blog/linq-expand-update.aspx.
这篇关于如何做Linq:“select * from Employee where ID in(10,11,12)”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!