11

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.

1
  • 3
    LINQ isn't a solution to every problem, what you have written is fine. Commented Feb 28, 2011 at 2:00

4 Answers 4

14

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));
Sign up to request clarification or add additional context in comments.

4 Comments

technically this isn't LINQ ;-)
technically it's not functional programming either - blogs.msdn.com/b/ericlippert/archive/2009/05/18/…
I knew there is always a better way than what I normally do. It works great. Thanks to you and Mike.
i want the same but how do i find part of string and replace it with some other text ? please suggest.
4

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

Comments

1

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";
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.