If your collection contains reference types then you can modify its items in-place by using an extension method, similar to the ForEach
method on List<T>
.
This is possible because you're not actually trying to alter the IEnumerable<T>
sequence: The collection contains references but you're only modifying the referenced objects, not the references themselves.
This technique won't work for collections of value types. In that case you would be trying to alter the read-only, IEnumerable<T>
sequence, which isn't possible.
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T item in source)
{
action(item);
}
}
// ...
public class Example
{
public int Value { get; set; }
}
// ...
Example[] examples =
{
new Example { Value = 1 }, new Example { Value = 2 },
new Example { Value = 3 }, new Example { Value = 4 }
};
examples.ForEach(x => x.Value *= 2);
// displays 2, 4, 6, 8
foreach (Example e in examples)
{
Console.WriteLine(e.Value);
}