Putting performance aside for a moment I'll start with the inline "elegant" (opinion based) solution for the question of a substitute for the traditional ForEach:
collection.ToList().ForEach(item => { item.DataList = item.Data.Split(';'); });
Now, looking at the ReferenceSource what actually stands behind ForEach
this is a simple loop:
for(int i = 0 ; i < _size; i++) {
/* O(1) code */
action(_items[i]);
}
Note that this is not a linq solution. It uses lambda expressions but ForEach
is not a function of linq
Now back to performance. There are two issues.
- The less significant one is that for each iteration of the internal loop there is another function call to the passed
Action
.
- The more significant one is that as described the object is an
IEnumerable<T>
. ForEach
is a method of IList
. Therefore there
is a call to ToList()
that creates a new collection at performs in
O(n)
which is not needed.
I'd just go with the simple straight forward solution of:
foreach(var item in collection)
{
item.DataList = item.Data.Split(';');
}
As a general note about linq:
- Linq is for manipulations on collections and not really for updating the items enumerated. Here an update operation is needed so linq is not the best fitting solution.
- Performance - For in-memory collection linq will only improve performance when the deffered execution is relevant and the non-linq implementation is not lazy. When working with linq-to-X such as to some database it is a complete different world and very much depends on the specific linq provider. As a whole it can help you perform operations in a single DB query where otherwise, if not implemented in the database, will be in several queries.
Worth reading: Is a LINQ statement faster than a 'foreach' loop?