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的组合。
答案 0 :(得分:9)
如果您真的想缩短代码,可以使用ForEach
上的List
扩展方法:
abbreviations.ForEach(x=> test=test.Replace(x.ShortName, x.LongName));
答案 1 :(得分:2)
您可以使用ForEach方法。此外,StringBuilder应该使字符串上的操作更有效:
var test = new StringBuilder("this is a test exp. in a para. contains ans. for a question");
abbreviations.ForEach(abb => test = test.Replace(abb.ShortName, abb.LongName));
return test.ToString();
答案 2 :(得分:1)
试试这个
TestList.ForEach(x => x.TestType.Replace("", "DataNotAvailable"));
或下面的那个
foreach (TestModel item in TestList.Where(x => x.ID == ""))
{
item.ID = "NoDataAvailable";
}