Home > Mobile >  How to cast a generic array into an actual numeric type array?
How to cast a generic array into an actual numeric type array?

Time:04-17

I want to add some values which are passed as a generic array.

I have tried the following code which is giving me compile time errors:

    public static T sum(T[] array)
    {
        TypeCode typeCode = Type.GetTypeCode(typeof(T));

        switch(typeCode)
        {
            case TypeCode.Double:
                IEnumerable<double> doubleIenumerable = Array.ConvertAll(array, x => (double)x);
                List<double> doubleArray = new List<double>(array);
                double doubleSum = 0;
                foreach (var item in doubleArray)
                {
                    doubleSum  = item;
                }
                return (T)Convert.ChangeType(doubleSum, typeof(T));
                ///////////////////////////////////////////////////
        }
    }

enter image description here

How can I cast a generic array into an actual numeric type array?

CodePudding user response:

You can make use of LINQs

Enumerable.Cast

Casts the elements of an IEnumerable to the specified type.

IEnumerable<double> doubleIenumerable = array.Cast<double>();

or

Enumerable.OfType

Filters the elements of an IQueryable based on a specified type.

IEnumerable<double> doubleIenumerable = array.OfType<double>();

CodePudding user response:

Try following :

       static void Main(string[] args)
        {
            double[] input = { 1.23, 4.56 };
            double results = sum(input);

        }
        public static T sum <T> (T[] array)
        {
            TypeCode typeCode = Type.GetTypeCode(typeof(T));
            T doubleSum = default(T);
            switch (typeCode)
            {
                case TypeCode.Double:
                    double[] doubleArray = array.Select(x => Convert.ToDouble(x)).ToArray();
                    double sum = doubleArray.Sum(x => x);
                    doubleSum = (T)Convert.ChangeType(sum, typeof(T));
                    break;
            }
            return doubleSum;

        }
  • Related