3

I have the following query that receives a list of ints as a parameter:

public int GetMostRecent(List<int> TheIDs)
{
 ...using MyDC...

   var TheMostRecentID = (from d in MyDC.Data
                           where TheIDs.Contains(d.ID)
                           orderby d.DateTime
                           select d.ID).LastOrDefault(); 
}

Is this the best way to match a list within a parameter collection to data in the database or is there a better way than using the .Contains() method in linq-to-sql.

Thanks.

1
  • Why are you looking for a better way? What do you think is bad about what you're doing now? Commented Jan 27, 2012 at 14:39

3 Answers 3

9

What you have is correct. This will be translated into an IN clause in SQL with the values supplied in the collection.

On an unrelated note, you should try ordering the query by date descending and use FirstOrDefault(). As it is now, you're going to bring back the entire result set and throw away every row but one.

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

1 Comment

LastOrDefault will even throw an error that this linq is not able to translate it into sql.
4

You should be careful with such queries with list.Contains() inside of linq query. Because for each list element it will create a param in sql statement.

And there's a limited number of params allowed in sql statement, <= 2100. So if your TheIDs will contains more than 2100 elements it will fail.

If you want to use in this way, you should at least check your TheIDs count and if more then 2100 dived it in pieces with less then 2100 elements.

Comments

1

This will translate into efficient SQL, so there's no need to use anything else.

Comments

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.