Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq where clause when id is in an array

Tags:

c#

linq

I have a method which should return list of Users if the UserId is in an array. The array of UserIds is passed to the method.

I'm not sure how to write ..where userid in array?

below in ids[] is clearly not correct.

public List<User> GetUsers(int[] ids)
{
   return Users.Values.Where(u => u.UserID in ids[]).ToList();
}

Any ideas how to correct that?

Thanks,

like image 254
thegunner Avatar asked Mar 07 '16 14:03

thegunner


2 Answers

You can try something like that :

public List<User> GetUsers(int[] ids)
{
    return Users.Values.Where(u => ids.Contains(u.UserID)).ToList();
}
like image 54
Quentin Roger Avatar answered Nov 10 '22 12:11

Quentin Roger


Alternatively to Quentins answer, use this:

public List<User> GetUsers(int[] ids)
{
    return Users.Values.Where(u => ids.Any(x => x == u.UserID)).ToList();
}
like image 37
MakePeaceGreatAgain Avatar answered Nov 10 '22 12:11

MakePeaceGreatAgain