Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string replace using Linq in c#


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.

like image 213
GaneshT Avatar asked Feb 28 '11 01:02

GaneshT


1 Answers

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));
like image 155
p.campbell Avatar answered Oct 18 '22 10:10

p.campbell