简体   繁体   中英

Most efficient way to concatenate string?

What is the best way to concatenate string to receive ukr:'Ukraine';rus:'Russia';fr:'France' result?

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.

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:

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.

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

the Enumerable.Aggregate method is pretty good.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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