ankur
ankur

Reputation: 4733

How do you convert a List of object to a one dimensional array?

I have a list of objects which look like this:

 public class Hub
    {
        public string Stamp { get; set; }
        public string Latency0 { get; set; }
        public string Latency1 { get; set; }
        public string Latency2 { get; set; }
        public string Latency3 { get; set; }
        public string Latency4 { get; set; }
    }

After I convert this list into a Json it looks like the image below.

enter image description here

How can I convert the list into the array shown in the image? Either I should be able to create a C# array which I can further convert into a Json array shown in the image.

enter image description here

I tried using this ToArray() on the list but it only converts it into an array of object.

Upvotes: 2

Views: 659

Answers (3)

Konamiman
Konamiman

Reputation: 50273

Aomine's answer is fine if you are fine with keeping your values as strings. However, your screenshot seems to suggest that you actually need these values converted to numbers. Since these can have decimals and can be null, decimal? is the type you need for that.

Start by creating this auxiliary method:

decimal? ParseOrNull(string value)
{
    decimal numericValue;
    return decimal.TryParse(value, out numericValue) ? numericValue : (decimal?)null;
}

And then:

hubs.Select(h => 
    new [] { h.Stamp, h.Latency0, h.Latency1, h.Latency2, h.Latency3, h.Latency4 }
            .Select(ParseOrNull).ToArray())
    .ToArray()

Upvotes: 1

Ivvan
Ivvan

Reputation: 730

Aomine is right, but if you want to get the result as array of doubles (or actually nullable doubles), you need to do convertion like this:

double temp;
source.Select(x => new string[]{
             x.Stamp, x.Latency0, x.Latency1, x.Latency2, x.Latency3, x.Latency4}
            .Select(n => double.TryParse(n, out temp) ? temp : (double?)null))
     .ToArray();

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56413

source.Select(x => new string[]{
             x.Stamp, x.Latency0, x.Latency1,
             x.Latency2, x.Latency3, x.Latency4})
      .ToArray();

Upvotes: 1

Related Questions