tags:

views:

50

answers:

1

I have two collections:

List<int> ids;
List<User> users;

Where User has id, name, etc.

I would like to inner join these two collections and return a new List<int> with ids from the first collection which are also in the second collection (User id's).

I am new to LINQ and don't know where to start.

Thanks.

+5  A: 

You don't need to use join to do this:

List<int> commonIds = ids.Intersect(users.Select(u => u.Id)).ToList();

EDIT: In response to the question in the comments, you could get a list of users without using Join:

var matchingUsers = users.Where(u => ids.Contains(u.Id));

However this is quite inefficient since the Where clause has to scan the list of ids for each user. I think Join would be the best way to handle this case:

List<User> matchingUsers = users.Join(ids, u => u.Id, id => id, (user, id) => user).ToList();
Lee
you beat me to it ;)
Thomas Levesque
Supposing OP wanted Users, not IDs. Could it still be done w/o a join?
spender
Just realized that my id's are actually long's and intersect function works only with int collections by default(?).
negative
nevermind,`List<long> commonIds = ids.Intersect<long>( users.Select<User, long>(u => (long)u.Id) ).ToList<long>();` works just fine
negative