使用LINQ连接字符串 [英] Using LINQ to concatenate strings

查看:81
本文介绍了使用LINQ连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最古老的写法是什么?

StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
    foreach (string s in strings)
    {
        sb.Append(s + ", ");
    }
    sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();

...在LINQ中吗?

...in LINQ?

推荐答案

此答案显示了问题中所要求的LINQ(Aggregate)的用法,并非日常使用.因为它不使用StringBuilder,所以对于很长的序列将具有可怕的性能.对于常规代码,请使用String.Join,如其他 answer

This answer shows usage of LINQ (Aggregate) as requested in the question and is not intended for everyday use. Because this does not use a StringBuilder it will have horrible performance for very long sequences. For regular code use String.Join as shown in the other answer

使用像这样的聚合查询:

Use aggregate queries like this:

string[] words = { "one", "two", "three" };
var res = words.Aggregate(
   "", // start with empty string to handle empty list case.
   (current, next) => current + ", " + next);
Console.WriteLine(res);

这将输出:

, one, two, three

集合是一个函数,它接受值的集合并返回标量值. T-SQL的示例包括min,max和sum. VB和C#都支持聚合. VB和C#都支持将聚合作为扩展方法.使用点符号,只需在 IEnumerable 对象.

An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.

请记住,聚合查询将立即执行.

Remember that aggregate queries are executed immediately.

更多信息- MSDN:聚合查询

如果您真的想使用Aggregate,请使用 CodeMonkeyKing 在注释中建议的使用StringBuilder的变体与常规String.Join几乎相同的代码,包括对大量对象的良好性能:

If you really want to use Aggregate use variant using StringBuilder proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join including good performance for large number of objects:

 var res = words.Aggregate(
     new StringBuilder(), 
     (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
     .ToString();

这篇关于使用LINQ连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆