更新集合C#中的对象

时间:2019-03-29 18:32:17

标签: c# entity-framework

我不了解如何更新集合中引用的对象。我的收藏:

List<Person> people

我想用更新的对象来更新人们的物品。

var existingPepe = people.Where(a => a.id ==someId).FirstOrDefault();
// on examintion existingperson.Age = 101;
Person person = new Person();
person.Age = 65;

现在用人员更新现有的Pepe;

existingPepe = person;

但这不会更新集合中的Person-对象年龄直到101为何?

6 个答案:

答案 0 :(得分:2)

  

“我应该如何更新现有的Pepe”

无需创建Person的新实例,您可以直接在现有找到的实例上更新属性Age。这会改变实际实例本身。这样做还意味着无需交换List<Person>中的项目。

// note that SingleOrDefault will throw an exception if there is more than one match
var foundPerson = people.SingleOrDefault(a => a.id ==someId);
if(foundPerson != null)
  foundPerson.Age = 65;
// else person with that id does not exist in the list

如果您希望在没有匹配项时引发异常,请改用Single。

var foundPerson = people.Single(a => a.id ==someId);
foundPerson.Age = 65;

答案 1 :(得分:1)

让我在这里帮助您。更新List的方法是获取对列表中正确位置的引用并对其进行更新。索引是使用列表的一种方法。

var indx = people.FindIndex(a => a.id == someId);
if (indx >= 0) {
    //people[indx].Age = 65; // in case you want to update the found record
    Person person = new Person();
    person.Age = 65;
    people[indx] = person; // set a new Person in the existing slot of the list
}

在这里,我使用List<T>.FindIndex函数来找到相关记录,然后使用该索引来更新现有记录,然后将该位置替换为新人员

更新

  

我想用更新的对象

更新人员中的项目

在此处回答一堆评论。我不能假设Personclassstruct,也不能知道它是immutable class。因此,我不能认为该字段是可更新的。另外,问题中的代码对于OP是要更新现有对象还是在该插槽中设置新对象,显然也含糊不清。两者都是非常常见的行为,因此我的示例演示了这两种行为,因此OP可以决定哪种方法适用于它们。

答案 2 :(得分:1)

变量existingPepe包含对从列表中选择的对象的引用。设置existingPepe = person;会将引用更改为指向新的Person对象。变量existingPepeperson现在指向/引用同一对象。原始列表对现有人员的引用不受后续操作的影响。您需要通过设置索引来更新对现有对象的列表引用,以指向您的新对象。

答案 3 :(得分:1)

如果要更新一个人。然后只需修改您在内存中找到的那个

var existingPepe = people.Where(a => a.id ==someId).FirstOrDefault();
existingPepe.Age = 65;

您过去的做法是创建一个新人员,而不将其添加到收藏夹中。

答案 4 :(得分:0)

如果您的目标是更新该集合中某人的年龄,则可以使用linq这样操作

people.Where(a => a.id == someId).Select(a => a.Age = 65; return a).ToList();

答案 5 :(得分:0)

如果要替换集合中的对象本身,请执行删除/添加操作:

if(people.Remove(people.Where(a => a.id ==someId).FirstOrDefault()))
people.Add(new Person {Age=65});