2011-02-28 33 views
7

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

böyle Kısaltma nesnelerin bir listesi var:dize C# Linq kullanarak yerine


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") 
... 

sonucun olmasını bekliyoruz: "Bu paragrafta bir test ifadesidir bir cevabını içeriyor sorusu"

Şu yapıyorum:


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

w daha iyi olup olmadığını merak Linq ve Regex bir arada kullanarak. Eğer gerçekten kodunuzu kısaltmak istiyorsa

+3

LINQ altında bir her soruna bir çözüm değildir deneyin Yazdığın şey iyi. – Phill

cevap

9

, sen List üzerinde ForEach uzatma yöntemi kullanabilirsiniz:

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

teknik olarak bu değil LINQ ;-) – BrokenGlass

+1

teknik olarak ya fonksiyonel programlama değil - http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx – RPM1984

+0

Her zaman normalde yaptığımdan daha iyi bir yol var. Harika çalışıyor. Sana ve Mike'a teşekkürler. – gangt

2

Sen ForEach yöntemi kullanabilirsiniz. Ayrıca, bir StringBuilder senin ipte işlemleri daha verimli hale olmalıdır:

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

bu bir

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

veya

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