Reputation: 4733
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.
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.
I tried using this ToArray()
on the list but it only converts it into an array of object.
Upvotes: 2
Views: 659
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
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
Reputation: 56413
source.Select(x => new string[]{
x.Stamp, x.Latency0, x.Latency1,
x.Latency2, x.Latency3, x.Latency4})
.ToArray();
Upvotes: 1