在C#中使用Linq进行字符串替换 [英] string replace using Linq in c#

查看:607
本文介绍了在C#中使用Linq进行字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


public class Abbreviation
{
    public string ShortName { get; set; }
    public string LongName { get; set; }
}

我有一个这样的缩写对象列表:

I have a list of Abbreviation objects like this:


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")
...

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

I expect the result to be: "this is a test expression in a paragraph contains answer for a question"

当前我正在做


foreach (Abbreviation abbreviation in abbreviations)
{
    test = test.Replace(abbreviation.ShortName, abbreviation.LongName);
}
result = test;

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

Wondering if there is a better way using a combination of Linq and Regex.

推荐答案

如果您确实想缩短代码,则可以在List上使用ForEach扩展方法:

If you really wanted to shorten your code, you could use the ForEach extension method on the List:

abbreviations.ForEach(x=> test=test.Replace(x.ShortName, x.LongName));

这篇关于在C#中使用Linq进行字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆