首页 > 解决方案 > 从逗号分隔的字符串在 C# 中设置对象

问题描述

我正在遍历 Umbraco 节点列表并使用每个节点上的属性值设置我的类的属性

foreach (var node in listOfNodeWithProperty)
{
    var faqProperties = new Faq
    {
        Question = node.GetPropertyValue<string>("question"),
        Answer = node.GetPropertyValue<string>("answer"),
        Schemes = node.GetPropertyValue<string>("schemes")
    };

    faqCollection.faqs.Add(faqProperties);

}

我的常见问题类如下

internal class Faq
{
    public string Question { get; set; }
    public string Answer { get; set; }
    public string Schemes { get; set; }
    public IEnumerable<SchemeTypes> SchemeTypes { get; set; } 
}

internal class SchemeTypes
{
    public string SchemeType { get; set; }
}

字符串的所有内容都直截了当,但我要填充 SchemeTypes 对象的值是逗号分隔的字符串。如何获取此字符串并创建一个数组来填充 SchemeTypes?

我希望 SchemeTypes 作为一个对象,因为我的最终输出将是 JSON

标签: c#

解决方案


It sounds like you just want to split on commas and project from that to SchemeTypes objects:

SchemeTypes = node.GetPropertyValue<string>("schemeTypes")
                  .Split(',')
                  .Select(t => new SchemeTypes { SchemeType = t })
                  .ToList() // Materialize the result

I would caution the use of SchemaTypes as a type name when it represents a single type though. I'd consider something like:

internal class SchemeType
{
    public string Name { get; set; }
}

That's if you really need a class for it though. You could just have an IEnumerable<string> property in Faq, and it would generate JSON of

schemeTypes = [ "a", "b", "c" ]

Whereas with the extra class you'll get

schemeTypes = [
   { "name": "a" },
   { "name": "b" },
   { "name": "c" }
]

Are you sure you want the latter formatting?

If you're happy with the property being an IEnumerable<string>, you can just stick with the result of string.Split:

var faqProperties = new Faq
{
    Question = node.GetPropertyValue<string>("question"),
    Answer = node.GetPropertyValue<string>("answer"),
    Schemes = node.GetPropertyValue<string>("schemes"),
    SchemeTypes = node.GetPropertyValue<string>("schemeTypes").Split(',')
};

推荐阅读