在 C# 中使用 Linq 进行字符串替换

问题描述 投票:0回答:4

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。

linq string replace using
4个回答
14
投票

如果你真的想缩短你的代码,你可以使用

ForEach
上的
List
扩展方法:

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

4
投票

您可以使用 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();

1
投票

试试这个

TestList.ForEach(x => x.TestType.Replace("", "DataNotAvailable"));

或者下面那个

foreach (TestModel item in TestList.Where(x => x.ID == ""))
{
    item.ID = "NoDataAvailable";
}

0
投票

var newList = someList.Select(s => s.Replace("XX", "1")).ToList();

© www.soinside.com 2019 - 2024. All rights reserved.