Monday, January 30, 2012

Best Extension Methods: Slice of Collection

This Extension method is to get a slice of collection from a collection.
  public static IEnumerable Slice(this IEnumerable collection, int start, int end)
            int index = 0;
            int count = 0;

            if (collection == null)
                throw new ArgumentNullException("collection");

            // Optimise item count for ICollection interfaces.
            if (collection is ICollection)
                count = ((ICollection)collection).Count;
            else if (collection is ICollection)
                count = ((ICollection)collection).Count;
                count = collection.Count();

            // Get start/end indexes, negative numbers start at the end of the collection.
            if (start < 0)
                start += count;

            if (end < 0)
                end += count;

            foreach (var item in collection)
                if (index >= end)
                    yield break;

                if (index >= start)
                    yield return item;


Compiled By: Rajesh Rolen

Share This!

No comments:

Powered By Blogger · Designed By Seo Blogger Templates