Reputation: 6167
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.
Upvotes: 7
Views: 16681
Reputation: 1306
Use like that
var subscriptionDetails = SubscriptionMasterBL.GetSubscriptionMasterDetails();
tempUserList = lstSubscriberUsers.Where(a => subscriptionDetails.Any(b => b.SubscriptionUserId == a.Id
&& b.TokenId != Guid.Empty)).ToList();
Upvotes: 0
Reputation: 1500545
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.)
Upvotes: 27