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

C# 如何将对象列表转换为一维数组?,c#,arrays,.net,linq,C#,Arrays,.net,Linq,我有一个如下所示的对象列表: 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 { g

我有一个如下所示的对象列表:

 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; }
    }
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();
将此列表转换为Json后,它看起来如下图所示

如何将列表转换为图像中显示的数组?或者我应该能够创建一个C#数组,我可以进一步将其转换为如图所示的Json数组


我尝试在列表中使用这个
ToArray()
,但它只将其转换为对象数组。

Aomine是正确的,但是如果您想将结果作为double数组(或实际上可以为null的double),则需要执行如下转换:

 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; }
    }
source.Select(x => new string[]{
             x.Stamp, x.Latency0, x.Latency1,
             x.Latency2, x.Latency3, x.Latency4})
      .ToArray();
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的答案是正确的。然而,您的屏幕截图似乎表明您实际上需要将这些值转换为数字。因为它们可以有小数,也可以为空,
decimal?
是您需要的类型

首先创建此辅助方法:

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

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

我认为OP的json示例可能重复显示
Latency
值应该是字符串
latency1:“120.02”
,如果序列化十进制值,则输出将是
latency1:120.02