A line of Code to Convert Array of Objects to List of Doubles

Ralph Burton 20 Reputation points
2023-11-13T22:06:46.7166667+00:00

Hi,

I am trying to come up with a line of code to convert a System.Array of type object to a List<double>. I am certain that all of the objects in the Array will be either integer or double.

I understand that LINQ cannot be used with System.Array.

// Input data

dynamic Loaded_Data_Table = new {
  Dim1 = new object [] { 1.23, 2, 4.83, 8.163, 16.323, 32.64,
                         64.128, 128.256, 256.512, 512.1024 } }; 

//  { Dim1 = System.Object[] }

Loaded_Data_Table.Dim1.GetType ();     //  System.Object[]
Loaded_Data_Table.Dim1[0].GetType ();  //  System.Double
Loaded_Data_Table.Dim1[1].GetType ();  //  System.Int32


This is the best that I can come up with so far.
It seems to work, but I think it can be done with code that doesn't look so ugly.


List<double>
   LIST_of_double_vals
       = new List<double>
              (Array.ConvertAll
                (Loaded_Data_Table.Dim1,
                 new Converter<object, double>
                      ( delegate (object x) 
                        {return ((IConvertible)x).ToDouble(null);}
              ) )     )
  //  System.Collections.Generic.List`1[System.Double]

LIST_of_double_vals.Count();    // 10
LIST_of_double_vals.Sum();      // 1026.1844
LIST_of_double_vals.Average();  //  102.61844


Can anyone do better than that?

Thanks!

Developer technologies .NET Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. gekka 12,206 Reputation points MVP Volunteer Moderator
    2023-11-13T22:46:20.79+00:00

    Cast<T> or OfType<T> can be used to convert from Array.

    var LIST_of_double_vals = (Loaded_Data_Table.Dim1 as System.Array)
            .Cast<IConvertible>() // or .OfType<IConvertible>()
            .Select(_ => _.ToDouble(null))
            .ToList();
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.