C # converting an array returned as a shared object to another base type

I have a C # method that uses object as a generic container to return a data array that can be declared using different data types. The following is a simplified example of such a method:

 void GetChannelData(string name, out object data) { // Depending on "name", the underlying type of // "data" can be different: int[], byte[], float[]... // Below I simply return int[] for the sake of example int[] intArray = { 0, 1, 2, 3, 4, 5 }; data = intArray; } 

I need to convert all returned array elements to double , but so far I have not been able to find a way. Ideally, I would like to accomplish something like:

 object objArray; GetChannelData("test", out objArray); double[] doubleArray = Array.ConvertAll<objArray.GetType().GetElementType(), double>(objArray, item => (double)item); 

Which miserably fails because ConvertAll does not accept types defined at runtime. I also tried intermediate conversions to the dynamic variable, but to no avail.

Is there a way to do this type conversion in a simple way?

+5
source share
3 answers

If you do not know the type at compile time, you can try to convert it.

 var array = (IEnumerable)objArray; var doubles = array.OfType<object>().Select(a => Convert.ToDouble(a)).ToArray(); 
+4
source

If you do not know the type of array elements at compile time:

 var doubleArray = (objArray as Array).OfType<object>() .Select(m => Convert.ToDouble(m)).ToArray(); 
+3
source

u can create an extension method.

  public static IEnumerable<T> Convert<T>(this IEnumerable source) { foreach (var item in source) yield return (T)System.Convert.ChangeType(item, typeof(T)); } 

using ..

  object objArray; GetChannelData("test", out objArray); var array = (IEnumerable)objArray; var doubleArray = array.Convert<double>().ToArray(); 
+1
source

Source: https://habr.com/ru/post/1264710/


All Articles