How to update an object in a List<> in C#

I have a List<> of custom objects.

I need to find an object in this list by some property which is unique and update another property of this object.

What is the quickest way to do it?

335006 次浏览

使用 Linq 查找您可以执行的对象:

var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;

但在这种情况下,您可能希望将 List 保存到 Dictionary 中,然后使用以下命令:

// ... define after getting the List/Enumerable/whatever
var dict = myList.ToDictionary(x => x.MyProperty);
// ... somewhere in code
MyObject found;
if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;

或者没有 Linq

foreach(MyObject obj in myList)
{
if(obj.prop == someValue)
{
obj.otherProp = newValue;
break;
}
}

只是为了加强柯尼格的回应。只要您正在处理的类是引用类型(比如类) ,他的答案就会有效。如果自定义对象是一个 struct,那么这就是一个值类型,并且 .FirstOrDefault的结果会给你一个它的本地副本,这意味着它不会持久地返回到集合中,如下例所示:

struct MyStruct
{
public int TheValue { get; set; }
}

测试代码:

List<MyStruct> coll = new List<MyStruct> {
new MyStruct {TheValue = 10},
new MyStruct {TheValue = 1},
new MyStruct {TheValue = 145},
};
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;


foreach (var myStruct in coll)
{
Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();

输出是10,1,145

将 struct 更改为类,输出为10、12、145

高温

也可以试试。

 _lstProductDetail.Where(S => S.ProductID == "")
.Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();
var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";

你可以这样做:

if (product != null) {
var products = Repository.Products;
var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
Repository.Products[indexOf] = product;
// or
Repository.Products[indexOf].prop = product.prop;
}

这是今天的一个新发现——在学习了 class/struct 参考课之后!

如果您的 知道项目将被找到,您可以使用 Linq 和“ Single”,因为 Single 返回一个变量..。

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;
//Find whether the element present in the existing list


if (myList.Any(x => x.key == "apple"))
{
//Get that Item
var item = myList.FirstOrDefault(x => x.key == ol."apple");
//update that item
item.Qty = "your new value";
}

我找到了一种不用 LINQ 的一行代码就能做到的方法:

yourList.Where(yourObject => yourObject.property == "yourSearchProperty").Select(yourObject => { yourObject.secondProperty = "yourNewProperty"; return yourObject; }).ToList();
var index = yourList.FindIndex(x => x.yourProperty == externalProperty);
if (index > -1)
{
yourList[index] = yourNewObject;
}

yourlist now has the updated object inside of it.

同样值得一提的是,Matt Roberts 所说的应用于类内的结构。

So even when you have a class (which will pass by reference, theoretically), a property which is a list of structs inside it will pass by value when you try to find it and change a value inside a given struct (on the list).

For instance (using the same code as Matt proposed):

ParentClass instance = new ParentClass();


var found = instance.ListofStruct.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;


foreach (var myStruct in instance.ListofStruct)
{
Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();


public class ParentClass
{
public List<MyStruct> ListofStruct { get; set; }
public struct MyStruct
{
public int TheValue { get; set; }
}


public ParentClass()
{
ListofStruct = new List<MyStruct>()
{
new MyStruct {TheValue = 10},
new MyStruct {TheValue = 1},
new MyStruct {TheValue = 145}
};
}
}

将输出: 10,1,145

而将 struct (在 ParentClass 内部)更改为类,如下所示:

public class ParentClass
{
public List<MySubClass> ListofClass { get; set; }
public class MySubClass
{
public int TheValue { get; set; }
}


public ParentClass()
{
ListofClass = new List<MySubClass>()
{
new MySubClass {TheValue = 10},
new MySubClass {TheValue = 1},
new MySubClass {TheValue = 145}
};
}
}

将输出: 10,12,145