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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With