更新时间:2022-05-26 22:34:25
如果可以更改contacts
列表中的对象,可以在foreach
中使用简单的Join
:
If you're fine with changing the objects in the contacts
list, you could use a simple Join
with foreach
:
foreach(var joined in contacts.Join(interviews,
o => o.UserId,
i => i.UserId,
(originalContact, i) => new {originalContact, i.CountBehaviorInterview}))
{
joined.originalContact.CountBehaviorInterview = joined.CountBehaviorInterview;
}
如果要创建ContactsByUser
的新实例,那么您正在寻找左外部联接,如下所示:
If you want to create new instances of ContactsByUser
, then you're looking for a left outer join, something like this:
var result = from i in contacts
join o in interviews on i.UserId equals o.UserId into j
from o in j.DefaultIfEmpty()
select new ContactsByUser
{
UserId = i.UserId,
Username = i.Username,
CountContacts = i.CountContacts,
CountBehaviorInterview = j.Any() ? j.Single().CountBehaviorInterview : 0
};
或者,使用其他方法(可能会更慢,具体取决于您的数据,但可能没有关系):
or, using a different method (may be slower, depending on your data, but probably doesn't matter):
var result = from i in contacts
from o in interviews.Where(k => k.UserId == i.UserId).DefaultIfEmpty()
select new ContactsByUser
{
UserId = i.UserId,
Username = i.Username,
CountContacts = i.CountContacts,
CountBehaviorInterview = o != null ? o.CountBehaviorInterview : 0
};