You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中从逗号分隔字符串设置对象?及Umbraco节点赋值实现

Hey Mike, let's work through your two technical needs step by step. I'll add some robust, practical code examples that fit right into your existing setup.

1. Setting Object Properties from Comma-Separated Strings in C#

I’m guessing your Faq class’s Schemes property is intended to be a collection (like a List<string>) instead of a plain string—since you’re pulling a comma-separated value from Umbraco. Let’s tweak your class first to support that, then handle the string conversion:

Step 1: Update the Faq Class

Add a typed collection for Schemes (and initialize it to avoid null reference issues):

internal class Faq
{
    public string Question { get; set; }
    public string Answer { get; set; }
    public List<string> Schemes { get; set; } = new List<string>(); // Initialize empty collection
}

Step 2: Convert Comma-Separated String to Collection

When pulling the schemes value from Umbraco, we’ll split the string, clean up whitespace, and filter out empty entries to make sure your Schemes property is always valid:

Schemes = node.GetPropertyValue<string>("schemes")
    ?.Split(',', StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Trim())
    .ToList() ?? new List<string>();

Breakdown of what this does:

  • ?. : Safely skips splitting if the Umbraco property value is null
  • StringSplitOptions.RemoveEmptyEntries: Automatically ignores empty strings from leading/trailing commas
  • Select(s => s.Trim()): Cleans up extra spaces around each scheme (e.g., turns "scheme1, scheme2" into ["scheme1", "scheme2"])
  • ?? new List<string>(): Falls back to an empty collection if the source value is null

If you need Schemes to stay a string (e.g., for display), you can standardize the format instead:

Schemes = string.Join(", ", node.GetPropertyValue<string>("schemes")
    ?.Split(',', StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Trim()) ?? Array.Empty<string>());

This turns messy comma-separated strings into clean, spaced ones like "scheme1, scheme2, scheme3".

2. Optimizing Umbraco Node Traversal & Faq Assignment

Your existing loop is a solid start—let’s make it more robust with null checks and clean property handling. Here’s the refined version that integrates the comma-separated string logic:

// Ensure the faqs collection is initialized to avoid null reference errors
if (faqCollection.faqs == null)
{
    faqCollection.faqs = new List<Faq>();
}

foreach (var node in listOfNodeWithProperty)
{
    // Skip null nodes to prevent runtime errors
    if (node == null) continue;

    var faqProperties = new Faq
    {
        // Trim whitespace and fall back to empty string for question/answer
        Question = node.GetPropertyValue<string>("question")?.Trim() ?? string.Empty,
        Answer = node.GetPropertyValue<string>("answer")?.Trim() ?? string.Empty,
        // Apply the comma-separated string conversion we covered earlier
        Schemes = node.GetPropertyValue<string>("schemes")
            ?.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(s => s.Trim())
            .ToList() ?? new List<string>()
    };

    faqCollection.faqs.Add(faqProperties);
}

Bonus: Use Umbraco Strongly-Typed Models (Umbraco 8+)

If you’re using Umbraco 8 or later, enable Models Builder to generate strongly-typed classes for your document types. This eliminates "magic strings" (like "question" or "answer") and catches errors at compile time:

// Assume your Umbraco document type has a strongly-typed model called FaqNode
foreach (var node in listOfNodeWithProperty.OfType<FaqNode>())
{
    var faqProperties = new Faq
    {
        Question = node.Question?.Trim() ?? string.Empty,
        Answer = node.Answer?.Trim() ?? string.Empty,
        Schemes = node.Schemes?
            .Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(s => s.Trim())
            .ToList() ?? new List<string>()
    };

    faqCollection.faqs.Add(faqProperties);
}

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:51:34