复习4【c#】:string.Join的用法

 

需求:有一个字典类型数据,要求输入及输出如下:

 后端处理代码如下:

using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;

namespace CloudCodeTest.Controllers
{
    public class StringJoinController : Controller
    {
        // GET: StringJoin
        public ActionResult Index()
        {
            var parentChildMap = new Dictionary<string, List<string>>()
            {
                { "Parent1", new List<string> { "Child1", "Child2", "Child3" } },
                { "Parent2", new List<string> { "Child4" } },
                { "Parent3", new List<string>() } // 没有子节点
            };

            StringBuilder sb = new StringBuilder();
            foreach (var parent in parentChildMap.Keys)
            {
                if (parentChildMap[parent].Count > 0)
                {
                    // 父节点名称
                    sb.Append($"<strong>{parent}:</strong>");

                    // 使用 string.Join 将子节点用逗号连接
                    sb.Append("<span> " + string.Join(", ", parentChildMap[parent]) + " </span>");
                }
                else
                {
                    // 没有子节点时,仅显示父节点名称
                    sb.Append($"<strong>{parent}</strong>");
                }

                // 每个父节点后添加换行
                sb.Append("<br>");
            }
            var finalNote = sb.ToString();

            return View();
        }
    }
}

使用string.Join的优点如下:(来自通义解释)

 其他边界点分析如下:(来自通义解释)

 

posted @ 2025-04-16 16:17  katesharing  阅读(7)  评论(0)    收藏  举报