我有一个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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)