C# Update a List from Another List

后端 未结 5 1410
别跟我提以往
别跟我提以往 2020-12-16 12:50

I have 2 List. The first one, lets call it ListA is more like a complete list and the second one ListB is a modified list. Now what I want to do i
5条回答
  •  被撕碎了的回忆
    2020-12-16 13:21

    As I consider, you want to update only an age. Also you don't need to use Where().First() you can use just First().

    foreach (var x in ListB)
    {
        var itemToChange = ListA.First(d => d.Name == x.Name).Age = x.Age;
    }
    

    If you are not sure, that item exists in ListA you should use FirstOrDefault() and if statement to check it.

    foreach (var x in ListB)
    {
        var itemToChange = ListA.FirstOrDefault(d => d.Name == x.Name);
        if (itemToChange != null)
             itemToChange.Age = x.Age;
    }
    

提交回复
热议问题