【发布时间】:2011-11-03 15:18:09
【问题描述】:
我有一个List<> 的自定义对象。
我需要通过一些唯一的属性在这个列表中找到一个对象,并更新这个对象的另一个属性。
最快的方法是什么?
【问题讨论】:
我有一个List<> 的自定义对象。
我需要通过一些唯一的属性在这个列表中找到一个对象,并更新这个对象的另一个属性。
最快的方法是什么?
【问题讨论】:
使用 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;
【讨论】:
obj 或 value(copy) 的引用吗?换句话说,列表中的对象会改变吗?
只是为了补充 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
将struct改成class,输出为10,12,145
HTH
【讨论】:
或者没有 linq
foreach(MyObject obj in myList)
{
if(obj.prop == someValue)
{
obj.otherProp = newValue;
break;
}
}
【讨论】:
也可以试试。
_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;
}
【讨论】:
这是今天的新发现 - 在学习了类/结构参考课程之后!
如果您知道会找到该项目,您可以使用 Linq 和“Single”,因为 Single 返回一个变量...
myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;
【讨论】:
我在一行代码中找到了一种方法:
yourList.Where(yourObject => yourObject.property == "yourSearchProperty").Select(yourObject => { yourObject.secondProperty = "yourNewProperty"; return yourObject; }).ToList();
【讨论】:
//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";
}
【讨论】: