tags:

views:

247

answers:

3

Working on Maths problems, I'm very fond of LINQ to Data.

I would like to know if LINQ is smart enough to avoid a cast like .ToArray() when the IEnumerable I work with is already an array. See example below:

/// <summary> Transforms an array of timeSeries into one ModelData. </summary>
public static ModelData ToModelData(this IEnumerable<TimeSerieInfo> timeSeries)
{
    var seriesArray = timeSeries as TimeSerieInfo[];
    return null != seriesArray ? 
     new ModelData(seriesArray) : 
     new ModelData(timeSeries.ToArray());
}

Does LINQ avoid the transformation to an array when the IEnumerable<TimeSerieInfo> timeSeries is already an array?

Thank you for help.

+2  A: 

I suspect that it will do what you ask and create a new array. Could you not change your constructor of ModelData to take an IEnumerable instead?

Jeff Yates
A: 

LINQ does create a copy of the array; it creates a System.Linq.Buffer<T>, which creates a copy of the array.

You can create your own extension method though:

public static TSource[] ToArrayPreserved<TSource>(this IEnumerable<TSource> source)
{
    return (source as TSource[]) ??  source.ToArray();
}
configurator
+2  A: 

LINQ creates a copy of the array, and this is the correct behaviour IMO. It would be highly confusing if calling ToArray() and then modifying the returned array sometimes modified the original collection and sometimes didn't.

Jon Skeet
Totally agree, it's the correct behaviour.
Jeff Yates
That's logic. Thank you very much
Matthieu Durut