连接字符串的最有效方法

本文关键字:有效 方法 字符串 连接 | 更新日期: 2023-09-27 18:25:02

连接字符串以接收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()在后台使用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加入该列表成员。

Enumerable.Aggregate方法非常好。

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

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

string tst = lst.Aggregate((base, current) => 
    $"{base};{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();