示例#1
0
        /// <summary>
        /// Creates a <see cref="T:System.Collections.Generic.List`1" /> of specified capacity from an <see cref="T:System.Collections.Generic.IEnumerable`1"/>.
        /// </summary>
        /// <param name="source">The <see cref="T:System.Collections.Generic.IEnumerable`1" /> to create a <see cref="T:System.Collections.Generic.List`1" /> from.</param>
        /// <param name="capacity">The number of elements that the new list can initially store.</param>
        /// <typeparam name="TItem">The type of the elements of <paramref name="source" />.</typeparam>
        /// <returns>A <see cref="T:System.Collections.Generic.List`1" /> that contains elements from the input sequence.</returns>
        public static List <TItem> ToList <TItem>(this IEnumerable <TItem> source, int capacity)
        {
            ArgumentValidator.EnsureArgumentIsGreaterThanOrEqual(capacity, 0, "capacity");

            var result = new List <TItem>(capacity);

            result.AddRange(source);
            return(result);
        }
示例#2
0
        /// <summary>
        /// Same as <code>sequence.ExtendWithDefaultsTo(length).Take(length).ToArray()</code>,
        /// but with a single allocation (of a resulting array).
        /// </summary>
        /// <param name="sequence">Source sequence.</param>
        /// <param name="length">The length of the resulting array.</param>
        /// <typeparam name="T">The sequence element type.</typeparam>
        /// <returns>The resulting array.</returns>
        /// <exception cref="ArgumentException"><paramref name="length"/> is negative.</exception>
        public static T[] ToArray <T>(this IEnumerable <T> sequence, int length)
        {
            ArgumentValidator.EnsureArgumentIsGreaterThanOrEqual(length, 0, nameof(length));

            if (length == 0)
            {
                return(Array.Empty <T>());
            }

            var result = new T[length];

            using (var e = sequence.GetEnumerator()) {
                for (var i = 0; i < length && e.MoveNext(); i++)
                {
                    result[i] = e.Current;
                }
            }
            return(result);
        }