c# - 从逗号分隔的字符串在 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
解决方案
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(',')
};
推荐阅读
- c# - 循环遍历集合时如何选择随机记录?
- c# - 如何从 .NET Core Rest API 发出一个流以在 Angular 中作为 observable 使用?
- python - 在使用 5 折交叉验证时,在高度不平衡的数据中混淆 F1 分数和 AUC 分数
- kubernetes - K8 DNS 无法解析
- python - python矩阵的组合
- c# - 如何通过单击按钮更改另一个对象的动画?
- linux - AWS EC2 的 SCAP 合规性检查器错误
- regex - 用正则表达式 Erlang/Pearl 替换或忽略多个子字符串
- sql - 更改 SQL Server Express 默认 R 库路径
- tableau-api - Tableau - 基于一阶筛选