Returns the slice of the collection between elements start and end - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Returns the slice of the collection between elements start and end

Demo Code


using System.Linq;
using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Returns the slice of the collection between elements start and end
        /// </summary>
        /// <typeparam name="T">Type of the collection</typeparam>
        /// <param name="collection">Collection to use</param>
        /// <param name="start">Start of the slice</param>
        /// <param name="end">End of the slice</param>
        /// <returns>result = collection@pre->at( start, end )</returns>
        public static IEnumerable<T> Slice<T>(this IEnumerable<T> collection, int start, int end)
        {//from w  w w  .  j ava2 s  .c  o  m
            var count = collection.Count();

            Ensure.IsTrue(start.Between(0, end) && end.Between(0, count), 
                          "The start '{0}' and end '{1}' should be between 0 and {2}", 
                          start, end, count);

            return collection.Where((e, i) => i.Between(start, end));
        }
}

Related Tutorials