在c#中使用Linq替换字符串

Gan*_*shT 8 linq string replace using


public class Abbreviation
{
    public string ShortName { get; set; }
    public string LongName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个缩写对象列表,如下所示:


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")
...
Run Code Online (Sandbox Code Playgroud)

我希望结果是:"这是一个段落中的测试表达式,包含一个问题的答案"

目前我在做:


foreach (Abbreviation abbreviation in abbreviations)
{
    test = test.Replace(abbreviation.ShortName, abbreviation.LongName);
}
result = test;
Run Code Online (Sandbox Code Playgroud)

想知道是否有更好的方法使用Linq和Regex的组合.

p.c*_*ell 9

如果您真的想缩短代码,可以在以下位置使用ForEach扩展方法List:

abbreviations.ForEach(x=> test=test.Replace(x.ShortName, x.LongName));
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,这不是LINQ ;-) (4认同)