c# – ToArray()是否针对数组进行了优化?

ReSharper建议枚举IEnumerable< T>到列表或数组,因为我有“可能的IEnumerable< T>的多个枚举”.

所建议的自动代码重新分解具有内置的一些优化以查看IEnumerable< T>在调用ToArray()之前已经是一个数组.

var list = source as T[] ?? source.ToArray();

>这个优化是不是已经内置了原始的LINQ方法
>如果没有,那么不这样做的动机是什么?

解决方法

不,没有这样的优化.如果source是ICollection,那么它将被复制到新数组.这是Buffer< T>的代码. struct,由Enumerable用于创建数组:
internal Buffer(IEnumerable<TElement> source)
{    
    TElement[] array = null;
    int length = 0;
    ICollection<TElement> is2 = source as ICollection<TElement>;
    if (is2 != null)
    {
         length = is2.Count;
         if (length > 0)
         {
             array = new TElement[length]; // create new array
             is2.copyTo(array,0); // copy items
         }
    }
    else // we don't care,because array is ICollection<TElement>

    this.items = array;
}

这里是Enumerable.ToArray()方法

public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    Buffer<TSource> buffer = new Buffer<TSource>(source);
    return buffer.ToArray(); // returns items
}

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么