C#从另一个列表更新列表

时间:2016-04-10 12:28:42

标签: c#

我有2 List<object>。第一个,让我们称之为ListA更像是一个完整的列表,第二个ListB是一个修改过的列表。现在我想做的是用ListB修改ListA。这是可行的,我该怎么做。这就是我到目前为止所做的工作但不起作用:

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;

编辑:视觉演示,描述了什么&#39;修改&#39;在我的情况下意味着

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

修改&#39;它,ListA应该看起来像:

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

4 个答案:

答案 0 :(得分:13)

我认为,您只想更新一个年龄。此外,您不需要使用只能使用Where().First()的{​​{1}}。

First()

如果您不确定,foreach (var x in ListB) { var itemToChange = ListA.First(d => d.Name == x.Name).Age = x.Age; } 中存在该项,则应使用ListA和if语句进行检查。

FirstOrDefault()

答案 1 :(得分:4)

Where and First返回IEnumerable - 您只能修改列表的节点,但不能重新分配。

选项0 - 通用方法

using System.Collections.Generic;

//...

   var itemToUpdate = ListA.FirstOrDefault(d => d.Name == x.Name);
   if (itemToUpdate != null) {
       ListA[ListA.IndexOf(itemToUpdate)] = x;
   }

选项1 - 实施更新方法或手动执行字段更新

ListA.First(d => d.Name == x.Name).Update(x);

答案 2 :(得分:3)

您可以根据ListBListA删除Id的所有元素,将ListB添加到ListA,然后使用Id进行排序。

var newlist = ListA.Where(s => !ListB.Any(p => p.Id == s.Id)).ToList();
newlist.AddRange(ListB);
ListA = newlist.OrderBy(o => o.Id).ToList();

答案 3 :(得分:0)

您还可以将Union方法与IEqualityComparer一起使用:

var newList = ListB.Union(ListA, new PersonEqualityComparer());

class PersonEqualityComparer : IEqualityComparer<Person>
{
    public bool Equals(Person person1, Person person2)
    {
        if (person1 == null && person2 == null)
            return true;
        else if ((person1 != null && person2 == null) ||
                (person1 == null && person2 != null))
            return false;

        return person1.Id.Equals(person2.Id);
    }

    public int GetHashCode(Person item)
    {
        return item.Id.GetHashCode();
    }
}