7

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.

2 Answers 2

27

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

Sign up to request clarification or add additional context in comments.

5 Comments

looks like that would work for my needs. Ill try it out. Thanks!
Unfortunately this becomes problematic when you have allot of ID's. You will get an error in the lines of The incoming request has too many parameters. The server supports a maximum of 2100 parameters as contains does not build the query using SELECT * FROM TABLE WHERE ID IN (x,y....z) but instead injects allot of parameters.
@ppumkin: Indeed, that ends up being an issue - and to be honest, I don't know what the EF-supported way of coping with that situation is.
I think I will just build and execute the query manually in this case. Since the ID's are generated from another query it is protected from SQL injections.. I hope. But I cant see any other way to do it either.. unless I use dapper.
@ppumkin: Depending on what you're doing, you could potentially split the query into multiple queries each of which uses the approach in the answer with a subset of IDs.
0

Use like that

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

1 Comment

This doesnt seem to work with a local collection of ID's... for some reason. Even though I read somewhere we should use Any() as its much faster than Contains() .. but didn't realise you could apply it to SQL queries.. any way I get the error Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.