LINQ动态查询

时间:2010-05-13 14:11:19

标签: linq dynamic

如何动态生成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

2 个答案:

答案 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)