public static IEnumerableSlice (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; else 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; ++index; } } }
Monday, January 30, 2012
Best Extension Methods: Slice of Collection
This Extension method is to get a slice of collection from a collection.
Share This!
Labels:
C#.NET,
Extension Methods
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment