Takes a number of elements from the specified collection from the specified starting index. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Takes a number of elements from the specified collection from the specified starting index.

Demo Code


using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;//w  w w. ja va 2  s.c o  m

public class Main{
        /// <summary>
        /// Takes a number of elements from the specified collection from the specified starting index.
        /// </summary>
        /// <param name="list">
        /// The <see cref="List{T}"/> to take items from.
        /// </param>
        /// <param name="startingIndex">
        /// The index to start at in the <see cref="List{T}"/>.
        /// </param>
        /// <param name="takeCount">
        /// The number of items to take from the starting index of the <see cref="List{T}"/>.
        /// </param>
        /// <typeparam name="T">
        /// The type of elements in the collection.
        /// </typeparam>
        /// <returns>
        /// Returns a collection of <see cref="T"/> items.
        /// </returns>
        public static IEnumerable<T> Take<T>(this List<T> list, int startingIndex, int takeCount)
        {
            var results = new List<T>();

            int itemsToTake = takeCount;

            if (list.Count - 1 - startingIndex > itemsToTake)
            {
                var items = list.GetRange(startingIndex, itemsToTake);
                results.AddRange(items);
            }
            else
            {
                itemsToTake = list.Count - startingIndex;
                if (itemsToTake > 0)
                {
                    var items = list.GetRange(startingIndex, itemsToTake);
                    results.AddRange(items);
                }
            }

            return results;
        }
        /// <summary>
        /// Adds the elements of the specified collection to the end of the <see cref="ICollection{T}"/>.
        /// </summary>
        /// <param name="collection">
        /// The <see cref="ICollection{T}"/> to add the specified collection of items to.
        /// </param>
        /// <param name="itemsToAdd">
        /// The collection whose elements should be added to the end of the <see cref="ICollection{T}"/>.
        /// </param>
        /// <typeparam name="T">
        /// The type of elements in the collection.
        /// </typeparam>
        public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> itemsToAdd)
        {
            if (collection == null || itemsToAdd == null)
            {
                return;
            }

            foreach (var item in itemsToAdd)
            {
                collection.Add(item);
            }
        }
}

Related Tutorials