如何动态生成LINQ查询:
int[] IDArray = {55, 36};
public IQueryable<ContactListView> FindAllContacts(int loggedUserID, int[] IDArray)
{
var result = (
from contact in db.Contacts
//Start of dynamic part...
where
contact.UserID == loggedUserID
foreach (var id in IDArray)
{
where contact.UserID == id
}
// End of dynamic part
orderby contact.ContactID descending
select new ContactListView
{
ContactID = contact.ContactID,
FirstName = contact.FirstName,
LastName = contact.LastName
});
return result;
}
谢谢,
ILE
答案 0 :(得分:3)
你不能只使用Contains
吗?我假设您要生成具有IN
子句的查询。这里有一个例子:Creating in queries with linq to sql。
int[] IDArray = {55, 36};
public IQueryable<ContactListView> FindAllContacts(int loggedUserID, int[] IDArray)
{
var result = (
from contact in db.Contacts
where contact.UserID == loggedUserID
&& IDArray.Contains( contact.UserID )
orderby contact.ContactID descending
select new ContactListView
{
ContactID = contact.ContactID,
FirstName = contact.FirstName,
LastName = contact.LastName
});
return result;
}
答案 1 :(得分:2)
您可能需要where IDArray.Contains(contact.UserID)