简体   繁体   English

将具有字符串属性的对象数组转换为 c# 中的字符串数组

[英]Convert array of objects with string property to an array of strings in c#

I'm trying to convert an array of objects that has a string property to an array of strings.我正在尝试将具有字符串属性的对象数组转换为字符串数组。

For example:例如:

"temperature_controlled_transport": [
        {
            "data": "0"
        },
        {
            "data": "test" 
        }
    ]

Should become:应该变成:

"temperature_controlled_transport": ["0", "1"]

I tried with the following code:我尝试使用以下代码:

TemperatureControlledTransport = Array.ConvertAll(pimproduct.Values.TemperatureControlledTransport, x => x.Data)

But when the object is null, this does not work and throws an exception.但是当 object 为 null 时,这不起作用并抛出异常。 How can I make this work with null values?如何使用 null 值进行这项工作?

Also, this code is inside the creation of an object, so I cant use if blocks:此外,这段代码在 object 的创建中,所以我不能使用 if 块:

SHEQdata = new SHEQdata
            {
                TemperatureControlledTransport = Array.ConvertAll(pimproduct.Values.TemperatureControlledTransport , x => x.Data)
            }

Also, I have to do this with ~40 properties, so if there is a better way of doing this, please let me know:)此外,我必须使用约 40 个属性来执行此操作,所以如果有更好的方法,请告诉我:)

Thank you!谢谢!

How about using the null-coalescing operator?使用空合并运算符怎么样?

TemperatureControlledTransport = Array.ConvertAll(pimproduct.Values.TemperatureControlledTransport ?? new TemperatureControlledTransport[] { }, x => x.Data)

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

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