asp.net-如何在C#中更新List <>中的对象

我有List<>的自定义对象。

我需要通过一些唯一的属性在此列表中找到一个对象,并更新该对象的另一个属性。

最快的方法是什么?

Burjua asked 2019-10-09T01:56:02Z
6个解决方案
85 votes

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

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

但是在这种情况下,您可能希望将列表保存到字典中,而改用它:

// ... 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;
Carsten answered 2019-10-09T01:56:19Z
20 votes

只是为了增加CKoenig的回应。 只要您要处理的类是引用类型(如类),他的答案就会起作用。 如果自定义对象是结构,则这是一个值类型,并且.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

将结构更改为类,输出为10,12,145

HTH

Matt Roberts answered 2019-10-09T01:56:59Z
11 votes

有无linq

foreach(MyObject obj in myList)
{
   if(obj.prop == someValue)
   {
     obj.otherProp = newValue;
     break;
   }
}
Erix answered 2019-10-09T01:57:23Z
6 votes

也可以尝试。

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();
BJ Patel answered 2019-10-09T01:57:47Z
4 votes
var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
listObject.RemoveAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";
listObject.Insert(itemIndex, item);
codeMonkey answered 2019-10-09T01:58:04Z
2 votes

您可以执行以下操作:

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;
}
Halimi answered 2019-10-09T01:58:28Z
translate from https://stackoverflow.com:/questions/7190016/how-to-update-an-object-in-a-list-in-c-sharp