public class Abbreviation
{
public string ShortName { get; set; }
public string LongName { get; set; }
}
我有一个缩写对象列表,如下所示:
List abbreviations = new List();
abbreviations.add(new Abbreviation() {ShortName = "exp.", LongName = "expression"});
abbreviations.add(new Abbreviation() {ShortName = "para.", LongName = "paragraph"});
abbreviations.add(new Abbreviation() {ShortName = "ans.", LongName = "answer"});
string test = "this is a test exp. in a para. contains ans. for a question";
string result = test.Replace("exp.", "expression")
...
我期望结果是:
“这是段落中的测试表达式,包含问题的答案”
目前我正在做:
foreach (Abbreviation abbreviation in abbreviations)
{
test = test.Replace(abbreviation.ShortName, abbreviation.LongName);
}
result = test;
想知道是否有更好的方法结合使用 Linq 和 Regex。
如果你真的想缩短你的代码,你可以使用ForEach
上的扩展方法List
:
abbreviations.ForEach(x=> test=test.Replace(x.ShortName, x.LongName));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)