Linq query using list or array of ids

c# entity-framework linq

Question

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.

1
5
3/2/2013 7:40:40 PM

Accepted Answer

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.)

21
3/2/2013 7:41:45 PM

Popular Answer

Use like that

 var subscriptionDetails = SubscriptionMasterBL.GetSubscriptionMasterDetails();
                tempUserList = lstSubscriberUsers.Where(a => subscriptionDetails.Any(b => b.SubscriptionUserId == a.Id 
                    && b.TokenId != Guid.Empty)).ToList();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow