Car*_*ten 88
使用Linq查找您可以执行的对象:
var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,您可能希望将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;
Run Code Online (Sandbox Code Playgroud)
Mat*_*rts 23
只是为了补充CKoenig的回应.只要您正在处理的类是引用类型(如类),他的答案就会起作用.如果自定义对象是一个结构体,这是一个值类型,结果.FirstOrDefault会给你一个本地副本,这意味着它不会持久存回到集合中,如下例所示:
struct MyStruct
{
public int TheValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
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();
Run Code Online (Sandbox Code Playgroud)
输出为10,1,145
将结构更改为类,输出为10,12,145
HTH
Eri*_*rix 14
或没有linq
foreach(MyObject obj in myList)
{
if(obj.prop == someValue)
{
obj.otherProp = newValue;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
也可以尝试。
_lstProductDetail.Where(S => S.ProductID == "")
.Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();
Run Code Online (Sandbox Code Playgroud)
var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以执行以下操作:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是今天的一个新发现 - 在学习了类/结构参考课之后!
如果您知道会找到该项目,则可以使用 Linq 和“Single” ,因为 Single 返回一个变量...
myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
181481 次 |
| 最近记录: |