C#从另一个列表更新列表 [英] C# Update a List from Another List

查看:48
本文介绍了C#从另一个列表更新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个 List< object> .第一个,让我们称之为ListA更像是一个完整列表,第二个ListB是一个修改后的列表.现在我要做的是用ListB修改ListA.这可行吗,我该怎么做.到目前为止,这是我目前无法使用的内容:

I have 2 List<object>. 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 is to modify ListA with ListB. Is this doable and how can I do it. This is what I have so far but doesn't work:

var ListB = _repository.Get(m => m.Approved == true).ToList();
foreach (var x in ListB)
{
  ListA.Where(d => d.Name == x.Name).First() = x;
}

return ListA;

可视化演示,描述在我的情况下修改"的含义

Visual Presentation to describe what 'modify' means in my situation

ListA
Id     Name      Age
1     John       14
2     Mark       15
3     Luke       13
4     Matthew    18

ListB
Id     Name      Age
2     Mark       0
4     Matthew    99

修改"后,ListA应该如下所示:

After 'modifying' it, ListA should look like:

ListA
Id     Name      Age
1     John       14
2     Mark       0
3     Luke       13
4     Matthew    99

推荐答案

我认为,您只想更新年龄.另外,您不需要使用 Where().First(),您可以只使用 First().

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;
}

如果不确定该项目是否存在于 ListA 中,则应使用 FirstOrDefault()和if语句进行检查.

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;
}

这篇关于C#从另一个列表更新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆