0

I have to List's.

List<User>

and

List<Friends>

In User are 10 Coloumns, one of them is "UserID", in Friends we havbe 4 Coloumns, one of them is "UserIDActive".

Now i Wanna have a new List in which only all Users are in it, which are also in Friends. Connected through the Coloum UserID == UserIDActive with have the same value.

How to do that? With .contain I can only check two Lists with the same objects in it.

4

2 回答 2

3

您可以通过简单的连接来做到这一点:

var matchingUsers = users
    .Join(friends, u => u.UserID, f => f.UserIDActive, (u, f) => u);

这个重载Join需要四个参数:

  1. 收藏加入
  2. 加入原始收藏的钥匙
  3. 加入集合的键加入
  4. 结果选择器

如果需要,您可以返回一个包含用户和朋友的匿名类型,如下所示:

var matches = users
    .Join(friends, u => u.UserID, f => f.UserIDActive, (u, f) => new
    {
        User = u,
        Friend = f
    });

如果您有重复的可能性,请务必使用Distinct

var matchingUsers = users
    .Join(friends, u => u.UserID, f => f.UserIDActive, (u, f) => u)
    .Distinct;
于 2013-09-07T17:33:00.507 回答
1

List<User> newUserList = Users.Where(user => Friends.Select(friend => friend.UserIDActive).Contains(user.UserID));

于 2013-09-07T17:31:02.943 回答