连接字符串最有效的方法?

时间:2012-02-19 17:48:38

标签: c# lambda concatenation

将字符串连接到接收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 = ????

5 个答案:

答案 0 :(得分: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 :(得分:1)

您可以覆盖Country类中的ToString方法以返回string.format("{0}:'{1}'", Code, Title)并使用string.join来加入该列表成员。

答案 2 :(得分:0)

Enumerable.Aggregate方法非常好。

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

答案 3 :(得分:0)

C# 6.0 中,您可以使用 string interpolation 来显示格式化的日期。

string tst = lst.Aggregate((base, current) => 
    $"{base};{current.Code}:'{current.Title}'");

答案 4 :(得分:-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();