C# Example: Split An Array into Multiple Smaller Arrays

Contents

  1. Example
  2. References
 

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)

This entry was posted in c# and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.