How to do a WHERE…IN… clause in LinqToSql?

吃可爱长大的小学妹 提交于 2019-12-10 10:47:13

问题


Bear with me, I'm beginning: How can I select multiple elements using a WHERE...IN... type of clause as in

select * from orders where orderid in (1, 4, 5)

in LinqToSql? I'd prefer not to have a lambda expression since they scare me. Thanks in advance!


回答1:


LINQ has "Contains" which is like "IN" but expressed the other way round - an element isn't "in" a set, a set "contains" an element.

int[] validIds = { 1, 4, 5 };
var query = from order in db.Orders
            where validIds.Contains(order.Id)
            select order

This is more simply expressed (IMO) with a lambda though:

int[] validIds = { 1, 4, 5 };
var query = db.Orders.Where(order => validIds.Contains(order.Id));

I realise lambdas are "new" and therefore scary to some extent, but it's really well worth grabbing hold of them with both hands. They're lovely.




回答2:


int[] arry = new int[] {1,4,5};

var q = from r in orders
        where Array.IndexOf(array, orderid) != -1
        select r;

or

List<int> lst = new List<int>(new int[] {1,4,5});
var q = from r in orders
        where lst.Contains(orderid);
        select r;


来源:https://stackoverflow.com/questions/317606/how-to-do-a-where-in-clause-in-linqtosql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!