开发者

string replace using Linq in c#

开发者 https://www.devze.com 2023-02-14 06:51 出处:网络
public class Abbreviation { public string ShortName { get; set; } public string LongName { get; set; } } I have a list of Abbreviation objects like this:

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"

Currently I am doing:


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

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


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));


You could use the ForEach method. Also, a StringBuilder should make the operations on your string more efficient:

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();


Try this one

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

or the one below

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号