Yar*_*ara 2 c# lambda concatenation
连接字符串以接收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 = ????
Run Code Online (Sandbox Code Playgroud)
我认为像这样的东西是相当可读的:
string tst = string.Join(";", lst.Select(x=> string.Format("{0}:'{1}'", x.Code, x.Title)));
Run Code Online (Sandbox Code Playgroud)
string.Join()正在使用StringBuilder引擎盖,因此在组装结果时不应该创建不必要的字符串.
由于参数to string.Join()只是一个IEnumerable(此重载所需的.NET 4),您还可以将其拆分为两行,以进一步提高可读性(在我看来),而不会影响性能:
var countryCodes = lst.Select(x=> string.Format("{0}:'{1}'", x.Code, x.Title));
string test = string.Join(";", countryCodes);
Run Code Online (Sandbox Code Playgroud)