Thursday, March 31, 2011

LINQ to Data : Clever Type Recognition.

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.

From stackoverflow
  • 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?

  • 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();
    }
    
  • 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.

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

0 comments:

Post a Comment