Count the number of elements in an array - CSharp System

CSharp examples for System:Array Element

Description

Count the number of elements in an array

Demo Code

/*/*from ww  w .  j ava2s  .c  o  m*/
    * Copyright: Thomas McGlynn 1997-2007.
    * 
    * The CSharpFITS package is a C# port of Tom McGlynn's
    * nom.tam.fits Java package, initially ported by  Samuel Carliles
    *
    * Copyright: 2007 Virtual Observatory - India.     
    *
    * Use is subject to license terms
    */
using System.Collections;
using System;

public class Main{
        /// <summary>Count the number of elements in an array</summary>
        public static int CountElements(Object o)
        {
            int result = 0;

            if (o.GetType().IsArray)
            {
                if (IsArrayOfArrays(o))
                {
                    for (IEnumerator i = ((Array)o).GetEnumerator(); i.MoveNext(); )
                    {
                        result += CountElements(i.Current);
                    }
                }
                else
                {
                    result = ((Array)o).Length;
                }
            }
            else
            {
                result = 1;
            }

            return result;
        }
}

Related Tutorials