Search list of objects based on object variable

后端 未结 4 751
独厮守ぢ
独厮守ぢ 2021-02-13 14:30

I have a list of objects. These objects have three variables, ID, Name, & value. There can be a lot of objects in this list, and I need to find one based on the ID or Name

4条回答
  •  逝去的感伤
    2021-02-13 15:11

    You could use LINQ to find it, then change the element directly:

    var item = TextPool.FirstOrDefault(o => o.Name == "test");
    if (item != null)
           item.value = "Value";
    

    If you wanted to change all elements that match, you could, potentially, even do:

    TextPool.Where(o => o.Name == "test").ToList().ForEach(o => o.value = "Value");
    

    However, I personally would rather split it up, as I feel the second option is less maintainable (doing operations which cause side effects directly on the query result "smells" to me)...

提交回复
热议问题