[ACCEPTED]-Change one field in an array using linq-linq
ForEach is sort of linq:
awards.ForEach(item => item.IncludeInReport = true);
But Linq is not 2 about updating values. So you are not using 1 the right tool.
Let me quantify "sort of linq". ForEach is not Linq, but a method on
List<T>
. However, the syntax is similar to Linq.
Here's the correct code:
awards = awards.Select(a => {a.IncludeInReport = true; return a;});
LINQ follows functional 7 programming ideas and thus doesn't want 6 you to change (mutate) existing variables.
So 5 instead in the code above we generate a 4 new list (haven't changed any existing values) and 3 then overwrite our original list (this is 2 outside LINQ so we no longer care about 1 functional programming ideas).
Since you are starting with an array, you 6 can use the Array.ForEach
method:
Array.ForEach(awards, a => a.IncludeInReport = true);
This isn't LINQ, but in this 5 case you don't need LINQ. As others have 4 mentioned, you can't mutate items via LINQ. If 3 you have a List<T>
you could use its ForEach
method in a similar 2 fashion. Eric Lippert discusses this issue 1 in more depth here: "foreach" vs "ForEach".
There is no mutating method available in 16 Linq. Linq is useful for querying, ordering, filtering, joining, and 15 projecting data. If you need to mutate it, you 14 already have a very clean, clear method 13 of doing so: your loop.
List<T>
exposes a ForEach
method 12 to write something that reminds you of Linq 11 (but isn't). You can then provide an Action<T>
or 10 some other delegate/function that applies 9 your mutation to each element in turn. (Ahmed 8 Mageed's answer also mentions the slightly different 7 Array.ForEach
method.) You can write your own extension 6 method to do the same with IEnumerable<T>
(which would 5 then be generally more applicable than either 4 aforementioned method and also be available 3 for your array). But I encourage you to 2 simply keep your loop, it's not exactly 1 dirty.
You can do something like that:
awards.AsParallel().ForAll(item => item.IncludeInReport = true)
That makes 1 that action parallel if possible.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.