Contents
Example
* Use Lambda expression to extends Array class to include a new method called Split:
public static class MyArrayExtensions { /// <summary> /// Splits an array into several smaller arrays. /// </summary> /// <typeparam name="T">The type of the array.</typeparam> /// <param name="array">The array to split.</param> /// <param name="size">The size of the smaller arrays.</param> /// <returns>An array containing smaller arrays.</returns> public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size) { for (var i = 0; i < (float)array.Length / size; i++) { yield return array.Skip(i * size).Take(size); } } }
* Test the new array class method:
[TestMethod] public void TestSplit2() { int[] array1 = new int[100]; for (int i = 0; i < array1.Length; i++) { array1[i] = i; } // Split into smaller arrays of maximal 30 elements IEnumerable<IEnumerable<int>> splited = array1.Split<int>(30); int j = 0; foreach (IEnumerable<int> s in splited){ j++; } log.InfoFormat("Splitted in to {0} smaller arrays.", j); }
References
* C#: Splitting an array into n parts
* Lambda Expressions (C# Programming Guide)