我有两个列表
List A List B ID FirstName DepartmentID ID FirstName DepartmentID 5 Peter Null 5 Peter 1 9 Steve Null 9 Steve 2 16 Mark Null 16 Mark 3
我想使用LINQ比较这些列表,如果两个列表中的ID相等,我想在第一个列表中设置DepartmentID,列表。
提前谢谢。
答案 0 :(得分:2)
ListA.ForEach(a=>a.DepartmentID = ListB.Any(b=>b.ID == a.ID) ? ListB.First(b=>b.ID == a.ID).DepartmentID : null);
编辑:如果要检查null。
答案 1 :(得分:1)
你可以加入他们。然后枚举结果并保存更改:
var results = from a in ListA
join b in ListB on ai.ID equals bi.ID
select new
{
itemA = a,
itemB = b
};
foreach(var result in results)
{
// This was not listed as a requirement, but it may be a valid check
if (itemA.FirstName == itemB.FirstName)
{
itemB.DepartmentID = itemA.DepartmentID;
}
}
DataContext.SubmitChanges();
答案 2 :(得分:1)
ListA.Join(ListB, x => x.ID, y => y.ID, (x, y) =>
{
x.DepartmentID = y.DepartmentID;
return 0;
}).ToArray();
答案 3 :(得分:0)
您可以使用其他列表并使用以下代码
var temp = from ai in ListA
join bi in ListB on ai.id equals bi.id
select bi;
var ListC = temp.ToList();
答案 4 :(得分:0)
var replacements = ListA
.Where(a => a.DepartmentID == null)
.Join(ListB,
a => a.ID,
b => b.ID,
(a, b) => new { Source = a, Replacement = b }
);
foreach (var item in replacements)
{
// here you could perform more replacements
item.Source.DepartmentID = item.Replacement.DepartmentID;
}