views:

46

answers:

2

How to dynamically generate LINQ query:

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;
}

Thanks,
Ile

+3  A: 

Can't you just use Contains? I assume you want to generate a query that has an IN clause. There's an example of that here: 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;
}
R0MANARMY
ile
`IDArray.Contains( id )`should be `IDArray.Contains( contact.UserID )`
Toby
Yes, that's it! Thank you!
ile
@Toby: Thanks for pointing that out, fixed the answer.
R0MANARMY
+1  A: 

You probably want where IDArray.Contains(contact.UserID)

UserControl
yes, that's it. thanks!
ile