Linq query using list or array of ids

c# entity-framework linq

Question

To retrieve all the objects corresponding to a list or array of ids and put them in a list, I need to query a database in C# using Linq. For instance:

I have an item table. I'm trying to create a method that returns every item whose ids are in a passed list or array. When I google it, it always believes that all I want to do is run a query against a list or array rather than a query that uses a list or array.

I appreciate it.

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

Accepted Answer

It seems like you would like:

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

Be aware that you may have a lot of acceptable IDs if this is all local (i.e., in-process, LINQ to Objects), therefore you should probably construct aHashSet<T> .

Or, of course, you might join:

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

(There are many examples of this on the internet, even on Stack Overflow, but I can understand that it's difficult to find one since all the terms you'd use are widely used.)

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

Popular Answer

Use in that way

 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