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

enxuqcxy  于 12个月前  发布在  C#
关注(0)|答案(4)|浏览(188)
public class Abbreviation
{
    public string ShortName { get; set; }
    public string LongName { get; set; }
}

字符串
我有一个这样的Abbreviable对象列表:

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的组合。

dtcbnfnu

dtcbnfnu1#

如果你真的想缩短你的代码,你可以在List上使用ForEach扩展方法:

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

字符串

iih3973s

iih3973s2#

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

字符串

0yycz8jy

0yycz8jy3#

试试这个

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

字符串
还是下面的那个

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

csga3l58

csga3l584#

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

相关问题