c#集合过滤,我从哪里开始呢?



我有一个集合,我们称之为'Users',也就是一组用户

用户有一组联系人。

我只是想获得给定用户与另一个用户的所有共同联系人。

我正在学习Lambda/Linq表达式,但不确定我是否应该这样做来解决这种类型的集合过滤问题。

所以实际上我只是在寻找两个集合的交集

不能在两个集合上简单地使用"=="。但是,如果联系人有某种类型的id,并且用户不能有相同的联系人两次,这是很容易做到的:

User user = ...
var contactIds = user.Contacts.Select(c => c.Id).ToArray();
var usersWithMatchingContacts = this.unitOfWork.UserRepository.Get()
    // basically, we're checking that the number of matching contacts is the same as the
    // total number of contacts for the user, which means that the user has the same
    // set of contacts. If you just want to require some overlap, change 
    // the "== u.Contacts.Count" to "> 0"
    .Where(u => u.Contacts.Count(c => contactIds.Contains(c.Id)) == u.Contacts.Count);
//input data
var firstId = 12;
var secondId = 23;
var firstUser = users.First(user => user.Id == firstId);
var secondUser = users.First(user => user.Id == secondId);
var commonContacts = firstUser.Contacts
                              .Where(contact =>
                                  secondUser.Contacts.Contains(contact))

使用LINQs相交方法

var commonContacts = firstUser.Contacts.Intersect(secondUser.Contacts)

最新更新