【问题标题】:Replace few variable names in the string for c#替换 c# 字符串中的几个变量名
【发布时间】:2022-11-03 14:59:05
【问题描述】:

我有一个问题,我的模板内容没有固定值,这个模板内容值是随机的,来自用户输入并存储在表格中,但是设置了内容的变量。

例如几个模板内容值(对于schedule.TemplateContent) :

1. My name is {name}.
2. My name is {name}. My last name is {lastName}
3. Her name is {name}. She is a {sex}. She like play {activity}

下面是我的代码,我只知道如何替换模板内容中的1个单词,不知道如何替换如果循环模板内容有多个变量需要替换:


foreach (SAASQueuePatList pat in patList)
{
pat.PatName = "{name}";
pat.PatLastName = "{lastName}";
pat.PatSex= "{sex}";
pat.PatActivity = "{activity}";

string fullContent = schedule.TemplateContent.Replace("{name}", pat.PatName);
}

希望有人能指导我如何解决这个问题。谢谢。

【问题讨论】:

    标签: c# for-loop replace


    【解决方案1】:
    string fullContent = schedule.TemplateContent
        .Replace("{name}", pat.PatName)
        .Replace("{lastName}", pat.PatLastName)
        .Replace("{sex}", pat.PatSex)
        .Replace("{activity}", pat.PatActivity);
    

    【讨论】:

      【解决方案2】:

      您需要一个将字段名称链接到属性的映射。

      var map = new Dictionary<string,Func<SAASQueuePat,string>>
      {
          "name", x => x.PatName,
          "sex", x => x.Gender
      };
      

      然后你可以生成这样的字符串:

      foreach (var item in map)
      {
          template.Replace("{" + item.Key + "}", item.Value(pat));
      }
      

      【讨论】:

        猜你喜欢
        • 2020-03-30
        • 2017-06-21
        • 2020-04-06
        • 2020-08-14
        • 1970-01-01
        • 2011-02-10
        • 2020-02-04
        • 1970-01-01
        相关资源
        最近更新 更多