替换c#字符串中的几个变量名



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

例如,少数模板内容值(对于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);
}

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

string fullContent = schedule.TemplateContent
.Replace("{name}", pat.PatName)
.Replace("{lastName}", pat.PatLastName)
.Replace("{sex}", pat.PatSex)
.Replace("{activity}", pat.PatActivity);

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

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

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

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

最新更新