Search code examples
c#lambdaconcatenation

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 = ????

Solution

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