list.Take(100).ToList() vs. list.GetRange(0,100)

前端 未结 5 1717
臣服心动
臣服心动 2021-02-19 11:57
List attendees = new List();
foreach ...
// Error: \"There are too many target users in the email address array\"
// for more tha         


        
5条回答
  •  孤街浪徒
    2021-02-19 12:23

    Here is GetRange implementation:

    public List GetRange(int index, int count)
    {
        if (index < 0)
        {
            ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
        }
        if (count < 0)
        {
            ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
        }
        if ((this._size - index) < count)
        {
            ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
        }
        List list = new List(count);
        Array.Copy(this._items, index, list._items, 0, count); // Implemented natively
        list._size = count;
        return list;
    }
    

    And this is Take Implementation

    public static IEnumerable Take(this IEnumerable source, int count)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        return TakeIterator(source, count);
    }
    
    private static IEnumerable TakeIterator(IEnumerable source, int count)
    {
        if (count > 0)
        {
            foreach (TSource iteratorVariable0 in source)
            {
                yield return iteratorVariable0;
                if (--count == 0)
                {
                    break;
                }
            }
        }
    }
    

    Plus ToList that simply does:

    public static List ToList(this IEnumerable source)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        return new List(source);
    }
    

    And List constructor:

    public List(IEnumerable collection)
    {
        if (collection == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
        }
        ICollection is2 = collection as ICollection;
        if (is2 != null)
        {
            int count = is2.Count;
            if (count == 0)
            {
                this._items = List._emptyArray;
            }
            else
            {
                this._items = new T[count];
                is2.CopyTo(this._items, 0);
                this._size = count;
            }
        }
        else
        {
            this._size = 0;
            this._items = List._emptyArray;
            using (IEnumerator enumerator = collection.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    this.Add(enumerator.Current);
                }
            }
        }
    }
    

    You can note immediately how much GetRange is cheaper against Take

提交回复
热议问题