问题
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:
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.
回答2:
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.
回答3:
This will translate into efficient SQL, so there's no need to use anything else.
来源:https://stackoverflow.com/questions/9034673/using-contains-with-linq-to-sql