2012-02-19 112 views
2

連接字符串以接收ukr:'Ukraine';rus:'Russia';fr:'France'結果的最佳方式是什麼?連接字符串的最有效方法是什麼?

public class Country 
{ 
    public int IdCountry { get; set; } 
    public string Code { get; set; } 
    public string Title { get; set; } 
} 

var lst = new List<Country>(); 
lst.Add(new Country(){IdCountry = 1, Code = "ukr", Title = "Ukraine"}); 
lst.Add(new Country() { IdCountry = 2, Code = "rus", Title = "Russia" }); 
lst.Add(new Country() { IdCountry = 3, Code = "fr", Title = "France" }); 
string tst = ???? 
+0

是您的目標模式真的'代碼: '標題';'後面'代碼: '標題','?注意第一對以分號結尾,第二對以逗號結尾。這是故意的嗎? – shanabus 2012-02-19 18:23:58

+0

可能重複[什麼是最好的字符串連接方法使用C#?](http://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c) – 2012-02-20 06:24:49

+0

shanabus,模式correcred,謝謝 – Yara 2012-02-20 15:23:27

回答

8

我覺得這樣的事情將是相當可讀:

string tst = string.Join(";", lst.Select(x=> string.Format("{0}:'{1}'", x.Code, x.Title))); 

string.Join()使用StringBuilder引擎蓋下所以這應該不會造成不必要的字符串,而組裝結果。

由於參數string.Join()只是一個IEnumerable(此重載需要.NET 4)您也可以拆分這一點到兩路,以進一步提高可讀性(在我看來),而不會影響性能:

var countryCodes = lst.Select(x=> string.Format("{0}:'{1}'", x.Code, x.Title)); 
string test = string.Join(";", countryCodes); 
+1

考慮用string.Concat(x.Code,「:'」,x.Title,「'」)替換string.Format(「...」)。 – Jason 2012-02-19 17:59:33

+2

@Jason - 我不同意:'string.Format'在內部使用'StringBuilder',所以我沒有看到使用'string.Concat()**和**的性能增益,它的可讀性差得多。 – BrokenGlass 2012-02-19 18:06:25

1

您可以覆蓋Country類中的ToString方法以返回string.format("{0}:'{1}'", Code, Title)並使用string.join來加入該列表成員。

+0

+1:在其他場景中促進重用的好方法。 – Douglas 2012-02-19 17:59:10

+0

元素之間的分號怎麼樣! – Lloyd 2012-02-19 18:04:35

+1

這將在'string.Join'內進行,如BrokenGlass的答案所示。代碼然後變得非常優雅:'string.Join(「;」,lst)'。 'Join'方法將負責在序列中的每個元素上調用'ToString'。 – Douglas 2012-02-19 18:11:40

0

Enumerable.Aggregate方法很不錯。

var tst = lst.Aggregate((base, current) => 
        base + ";" + String.Format("{0}:'{1}'", current.Code, current.Title)); 
-1

稍微有效的方式爲LINQ往往趨向於不太有效然後簡單foreachfor(在這種情況下)循環。

全部取決於什麼確切地說您的意思,通過說「最有效的方式」。

擴展方法:

public static string ContriesToString(this List<Country> list) 
{ 
    var result = new StringBuilder(); 
    for(int i=0; i<list.Count;i++) 
     result.Add(string.Format("{0}:'{1}';", list[i].Code, list[i].Title)); 

    result.ToString(); 
} 

使用:

var lst = new List<Country>(); 
lst.Add(new Country(){IdCountry = 1, Code = "ukr", Title = "Ukraine"}); 
lst.Add(new Country() { IdCountry = 2, Code = "rus", Title = "Russia" }); 
lst.Add(new Country() { IdCountry = 3, Code = "fr", Title = "France" }); 
string tst = lst.ContriesToString(); 
+0

這將提供ukr:Ukrainerus:俄羅斯:法國,是那個意圖? – Lloyd 2012-02-19 18:03:46

+0

@Lloyd:通過代碼提供的方式不是爲了複製粘貼,而是爲了想法探索。 – Tigran 2012-02-19 18:11:18

+0

這就是爲什麼我問我沒有標記,只是檢查。 – Lloyd 2012-02-19 18:29:41

相關問題