11

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,

4
  • 1
    the annoyances of typing up a reply to see someones already posted the same thing and a few people are already voting it.. so I deleted it
    – BugFinder
    Mar 7, 2016 at 14:14
  • 2
    @BugFinder This is an old problem which has its own name (Fastest Gun in the West). Mar 7, 2016 at 14:16
  • Thanks :) I just hate to see 2 answers the same, its pointless.. even if both are right.
    – BugFinder
    Mar 7, 2016 at 14:16
  • Possible duplicate of Where IN clause in LINQ Mar 7, 2016 at 14:23

2 Answers 2

26

You can try something like that :

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

Alternatively to Quentins answer, use this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.