C#两个list集合实现关联,将一个集合的某列属性值赋给另一个集合的某个属性列
有两个list,listA 和listB,
listA中有三个属性列为StoreId、OrderCount,StaffCount,
listB中有两个属性列为StoreId、StaffCount,
listA中当前StaffCount列为空,listB中两列都不为空,如何使用linq将listB的StaffCount列的值赋给listA,对应关系为listA.StoreId=listB.StoreId
方法一:linq方法语法
var listA = ...; var listB = ...; listA.ForEach(m => { var s = listB.FirstOrDefault(n => n.StoreId == m.StoreId); if(s != null) { m.StaffCount = s.StaffCount; } } );
法二:linq查询语法
listA = (from a in listA join b in listB on a.StoreId equas b.StoreId into ab from ba in ab.DefaultIfEmpty(new ModelXXXB()) select new ModelXXXA { StoreId = a.StoreId, OrderCount = a.OrderCount, StaffCount = ba.StaffCount } ).ToList()