Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query using list or array of ids

I am having trouble figuring out how to query a db using linq in c# to get all the objects corresponding to a list or array of ids and put them in a list. For example:

I have a table of items. I want to build a method that retrieves all the items whose ids are in a passes array or list. I have googled it but it always assumes i just want to query against a list or array rather than query USING a list or array.

Thanks in advance.

like image 246
jensengar Avatar asked Mar 02 '13 19:03

jensengar


1 Answers

Sounds like you want something like:

var query = items.Where(item => validIds.Contains(item.Id));

Note that if this is all local (i.e. in-process, LINQ to Objects) and you may have a lot of valid IDs, you probably want to construct a HashSet<T>.

Or you could do a join, of course:

var query = from id in validIds
            join item in items on id equals item.Id
            select item;

(There are lots of examples of this on the web and even on Stack Overflow, but I can understand that it's not an easy one to find as all the terms you'd use are common.)

like image 93
Jon Skeet Avatar answered Oct 21 '22 04:10

Jon Skeet