简体   繁体   English

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

[英]Most efficient way to concatenate string?

What is the best way to concatenate string to receive ukr:'Ukraine';rus:'Russia';fr:'France' result?连接字符串以接收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 = ????

I think something like this would be fairly readable:我认为这样的事情是相当可读的:

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

string.Join() is using a StringBuilder under the hood so this should not be creating unnecessary strings while assembling the result. string.Join()string.Join()使用StringBuilder ,因此在组装结果时不应创建不必要的字符串。

Since the parameter to string.Join() is just an IEnumerable (.NET 4 required for this overload) you can also split this out into two lines to further improve readability (in my opinion) without impacting performance:由于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 加入该列表成员。

In C# 6.0 you can use string interpolation in order to display formatted dates.C# 6.0您可以使用字符串插值来显示格式化的日期。

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

the Enumerable.Aggregate method is pretty good. Enumerable.Aggregate方法非常好。

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

Slightly efficient way as LINQ tends often to be less efficient then simple foreach or for (in this case) loop.作为LINQ稍微有效的方法往往不如简单的foreachfor (在这种情况下)循环效率低。

All depends on what exactly you mean, by saying "most efficient way".一切都取决于您的确切意思,即“最有效的方式”。

Extension method:扩展方法:

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();
}

use:用:

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