繁体   English   中英

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

[英]Most efficient way to concatenate string?

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

我认为这样的事情是相当可读的:

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

string.Join()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);

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

C# 6.0您可以使用字符串插值来显示格式化的日期。

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

Enumerable.Aggregate方法非常好。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM