Jason
Jason

Reputation: 113

Calling ToList() on Linq Select

I'm trying to iterate a collection call the TransformCvlValue for each record.

fields?.Select(x => TransformCvlValue(x, cvl)).ToList();

If I call .ToList() it works as expected. Why does .ToList() need to be called?

Is there another way of doing this?

Upvotes: 3

Views: 2149

Answers (1)

GeorgDangl
GeorgDangl

Reputation: 2192

Calling Select() on an IEnumerable<T> does not immediately execute the action but builds a new IEnumerable<T> with the specified transform / action. Generally, LINQ extension methods are only called when IEnumerable<T>s are materialized, for example via iterating over them in a foreach or by calling .ToList().

Select() should mostly be used when you really want to project elements from one type to another, e.g. by applying a projection to an element. It should not be used when you want to call a method for every element in an IEnumerable<T>.

Probably the most readable straightforward way for me would be to simply iterate over the fields:

if (fields != null)
{
    foreach (var field in fields)
    {
        TransformCvlValue(field, cvl);
    }
}

This makes clear what you intend the code to do and is easy to understand when you or your colleagues have to maintain the code in the future.

Upvotes: 4

Related Questions