.net 如何根据另一个对象列表更新列表中的对象

8yparm6h  于 2023-02-14  发布在  .NET
关注(0)|答案(2)|浏览(151)

我有两个列表如下:

var listA = new List<CompanyContact>(listAItems);
var listB = new List<CompanyContactDto>(listBItems);

public class CompanyContact
    {
        public string Id { get; set; }

        public string ContactId { get; set; }

        public bool IsMainContact { get; set; }

        public string Email { get; set; }
    }

public class CompanyContactDto
    {
        public string CompanyId { get; set; }
        public string ContactId { get; set; }
        public DateTime LastSavedDateTime { get; set; }
        public string Email { get; set; }
    }

现在我想将email属性从列表B复制到列表A,其中contactId在两个列表中是相同的。

var contacts = mapper.Map(listA, listA);

但它使其他项目无效

vlf7wbxs

vlf7wbxs1#

不如这样,

var aLookup = listA.ToLookup(a => a.ContactId);

foreach (var b in listB)
{
   foreach(var a in aLookup[b.ContactId])
   {
       a.Email = b.Email;
   }
}

或者,使用较少的代码,

foreach ((var a, var b) in aList.Join(
                                    bList,
                                    a => a.ContactId,
                                    b => b.ContactId,
                                    (a, b) => (a, b)))
{
    a.Email = b.Email;
}
iqih9akk

iqih9akk2#

foreach (var companyContactDto in listB)
{
    var matchingContacts = listA.Where(c => c.ContactId == companyContactDto.ContactId);
    
    foreach (var companyContact in matchingContacts)
    {
        companyContact.Email = companyContactDto.Email;
    }
}

使用字典仅枚举listA一次:

var contactsByContactId = listA.ToDictionary(c => c.ContactId);

foreach (var companyContactDto in listB)
{
    if (contactsByContactId.TryGetValue(companyContactDto.ContactId, out var matchingContact)
    {
        matchingContact.Email = companyContactDto.Email;
    }
}

相关问题