C# 连接字符串的最有效方法?
连接字符串以接收C# 连接字符串的最有效方法?,c#,lambda,concatenation,C#,Lambda,Concatenation,连接字符串以接收ukr:“乌克兰”的最佳方式是什么;罗斯:“俄罗斯”;fr:“法国”结果 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(){IdCoun
ukr:“乌克兰”的最佳方式是什么;罗斯:“俄罗斯”;fr:“法国”
结果
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 = ????
公共类国家
{
public int IdCountry{get;set;}
公共字符串代码{get;set;}
公共字符串标题{get;set;}
}
var lst=新列表();
lst.Add(新国家(){IdCountry=1,Code=“ukr”,Title=“乌克兰”});
lst.Add(新国家(){IdCountry=2,Code=“rus”,Title=“rusia”});
lst.Add(newcountry(){IdCountry=3,Code=“fr”,Title=“France”});
字符串tst=????
我认为这样的内容应该是相当可读的:
string tst = string.Join(";", lst.Select(x=> string.Format("{0}:'{1}'", x.Code, x.Title)));
string.Join()
由于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));
稍有效率的方式,如
LINQ
往往比简单的foreach
或for
(在本例中)循环效率更低
这一切都取决于你所说的“最有效的方式”的确切含义
扩展方法:
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 result=新的StringBuilder();
对于(int i=0;iConsider将string.Format(“…”)替换为string.Concat(x.Code,“:”,x.Title,“”)。@Jason-我不同意:string.Format
在内部使用StringBuilder
,因此我看不到使用string.Concat()的性能提升
而且可读性要差得多。这将带来ukr:Ukrainerus:Russiafr:France,这是有意的吗?@Lloyd:更正,顺便说一下,提供代码不是为了复制粘贴,而是为了探索想法。所以希望著名的downvoter解释他对这篇和其他10千万篇文章的否决票。元素之间的分号呢?那将是go在string.Join
中,如BrokenGlass的回答所示。然后代码变得非常优雅:string.Join(“;”,lst)
。Join
方法将负责对序列中的每个元素调用ToString
。您的目标模式真的是code:'Title';
后跟code:'Title',
?注意第一对以分号结尾,第二对以逗号结尾。这是故意的吗?可能是宾夕法尼亚州shanabus的重复谢谢你
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();