2011-02-28 81 views
7

public class Abbreviation 
{ 
    public string ShortName { get; set; } 
    public string LongName { get; set; } 
} 

我有這樣的縮寫對象的列表:字符串替換在C#中使用LINQ


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; 

不知道是否有一個更好的w ^使用Linq和Regex的組合。

+3

LINQ是不是每一個問題的解決方案,你寫的是好的。 – Phill 2011-02-28 02:00:10

回答

9

如果你真的想縮短你的代碼,你可以使用的ListForEach擴展方法:

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

從技術上講,這不是LINQ ;-) – BrokenGlass 2011-02-28 03:06:27

+1

在技術上它不是函數式編程 - http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx – RPM1984 2011-02-28 03:53:43

+0

我知道總有比我平常做的更好的方式。它效果很好。感謝你和邁克。 – gangt 2011-02-28 05:34:19

2

你可以使用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"; 
}