我有兩個清單。ListA 和 ListB。
串列A
ID Name Age
001 Andy null
002 Sam null
串列B
ID Name Age
001 Andy 10
我想要做的是根據兩個條件使用 ListB'Age 替換 ListA's Age Linq。他們是
ListA.ID == ListB.ID
ListA.Name == ListB.Name
因此,最終結果將是:
ID Name Age
001 Andy 10
002 Sam null
請忽略列名,因為它們僅用于演示目的。
uj5u.com熱心網友回復:
您可以使用 Linq,其概念是listALEFT JOIN listB。
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 小提琴示例
uj5u.com熱心網友回復:
給定兩個專案串列
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);
uj5u.com熱心網友回復:
使用 foreach 和 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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/484093.html
下一篇:在Linq查詢中使用“out”
