views:

43

answers:

3

Hi,

Using linqtosql, how would I get a colleciton of User objects, if I have an array of UserID's that I want to fetch?

+3  A: 

You can use Contains to check if each UserID is in the array that you have.

int[] userIDs = ...
var users = db.Users.Where( u => userIDs.Contains( u.UserID ) );
tvanfosson
this is the answer. The IENumerable.Contains() method used in LINQtoSQL expressions will generate a SQL IN() function.
andy
A: 

Try this:

using(var db=new MyDataContext())
{
    var users=db.Users.Where(u=>userIds.Contains(u.Id));
}
spender
I just want to note that this generates a pretty ugly query that uses SET comparisons (IN) instead of just generating a long WHERE clause.
FlySwat
+1  A: 

If you want to avoid a SET operation and user chained ORs instead, you can use the PredicateBuilder to help you with that.

It goes something like this:

var userIDs = new[] { 1, 2, 3, 4, 5 };

// build multiple OR expressions
var filter = PredicateBuilder.False<User>();

foreach (var id in userIDs) {
    filter = filter.Or(x => x.UserID == id);
}

// fetch data
using (var db = new TheDataContext()) {

    var users = db.Users.Where(filter);

    // wham! - we have users now.

}

Take a look at the blog post to understand how it works. This basically creates a long chaining ORs for each user id in the list before passing it to a WHERE clauses.

chakrit