根据多个条件将列表项值替换为另一个列表项值



我有两个列表。ListA和ListB.

ID  Name    Age
001 Andy    null
002 Sam     null

ListB

ID  Name    Age
001 Andy    10

我想做的是根据Linq的两个条件将ListA的Age替换为ListB的Age。他们是

ListA.ID == ListB.ID 
ListA.Name == ListB.Name

那么,最终的结果将是:

ID  Name    Age
001 Andy    10
002 Sam     null

请忽略列名,因为它们仅用于演示。

您可以使用Linq,概念是listALEFT JOINlistB

var result = (from a in listA
join b in listB on new { a.ID, a.Name } equals new { b.ID, b.Name } into ab
from b in ab.DefaultIfEmpty()
select new People
{
ID = a.ID,
Name = a.Name,
Age = b?.Age
}
).ToList();

示例。net Fiddle

给定两个项目列表

List<ListItem> listA = new List<ListItem>();
List<ListItem> listB = new List<ListItem>();

public class ListItem 
{
public string ID { get; set; }
public string Name { get; set; }
public int? Age { get; set; }
}

你可以这样改变listA的Age值:

listA.ForEach(item => 
item.Age = listB.Where(itemB => itemB.ID == item.ID && itemB.Name == item.Name)
.FirstOrDefault()?.Age);

using foreach and linq

public class emp
{
public string ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
var ListA = new List<emp>();
var ListB = new List<emp>();
ListA.Add(new emp { ID = "001", Name = "Andy" });
ListA.Add(new emp { ID = "002", Name = "Sam" });
ListB.Add(new emp { ID = "001", Name = "Andy", Age = 10 });
foreach (var emp in ListA)
{
var empfound = ListB.FirstOrDefault(lista => lista.ID == emp.ID);
if (empfound != null) emp.Age = empfound.Age;
}
}

最新更新