It does not work with List<string> because your solution is not modifying
the list object itself (as needed by the OP). it is modifying individual
objects referenced by the list.
Your solution is not actually LINQ, but it uses List<T> members that
could be thought of LINQ predecessors. As such, it is "LINQ-like".
A LINQ solution that would address the OP's needs would look more like this:
List<string> list = ...;
list.Aggregate(0, (i, x) =>
{
if (x == "image/pjpeg")
{
list
= "image/jpeg";
}
return i + 1;
});
As you can see, it is so wordy that it is hardly any better than an
explicit loop. But the real fatal flaw is that because Aggregate() is
using the IEnumerable<string> from the list, once you try to modify an
element of the list, the attempt to retrieve the next element fails with
an exception.
Sticking with the List<T> members, as in your example, you still wind up
with something like this:
List<string> list = ...;
int i = 0;
list.ForEach(x =>
{
if (x == "image/pjpeg")
{
list = "image/jpeg";
}
i++;
});
This avoids the exception, because the ForEach() method iterates through
the list elements explicitly and does not care if you modify the
collection while it is doing that.
But, the syntax really is not any better than an explicit loop, even so.
Pete