简体   繁体   English

如何将对象列表转换为一维数组?

[英]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. 将列表转换为Json后,如下图所示。

在此处输入图片说明

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. 我应该能够创建一个C#数组,然后将其进一步转换为图像中所示的Json数组。

在此处输入图片说明

I tried using this ToArray() on the list but it only converts it into an array of object. 我尝试在列表上使用此ToArray() ,但它仅将其转换为对象数组。

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

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: Aomine是正确的,但是如果您想以双精度数组(或实际上为可为空的双精度数组)的形式获取结果,则需要执行以下转换:

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();

Aomine's answer is fine if you are fine with keeping your values as strings. 如果可以将值保持为字符串,Aomine的答案很好。 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? 由于这些可以有小数,可以为空,所以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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM