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));
///////////////////////////////////////////////////
}
}
How can I cast a generic array into an actual numeric type array?
CodePudding user response:
You can make use of LINQs
Casts the elements of an IEnumerable to the specified type.
IEnumerable<double> doubleIenumerable = array.Cast<double>();
or
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;
}