How to update an element with a List using LINQ and C#

Addie picture Addie · Mar 15, 2010 · Viewed 59.1k times · Source

I have a list of objects and I'd like to update a particular member variable within one of the objects. I understand LINQ is designed for query and not meant to update lists of immutable data. What would be the best way to accomplish this? I do not need to use LINQ for the solution if it is not most efficient.

Would creating an Update extension method work? If so how would I go about doing that?

EXAMPLE:
(from trade in CrudeBalancedList
 where trade.Date.Month == monthIndex
 select trade).Update(
 trade => trade.Buy += optionQty);

Answer

Patrick Karcher picture Patrick Karcher · Mar 15, 2010

Although linq is not meant to update lists of immutable data, it is very handy for getting the items that you want to update. I think for you this would be:

(from trade in CrudeBalancedList
    where trade.Date.Month == monthIndex
    select trade).ToList().ForEach( trade => trade.Buy += optionQty);