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

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

问题描述

写老派最有效的方法是什么:

StringBuilder sb = new StringBuilder();if (strings.Count > 0){foreach(字符串中的字符串){sb.Append(s + ", ");}sb.Remove(sb.Length - 2, 2);}返回 sb.ToString();

...在 LINQ 中?

解决方案

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

像这样使用聚合查询:

string[] words = { "一", "二", "三" };var res = words.Aggregate("",//从空字符串开始处理空列表情况.(当前,下一个)=>当前 + ", " + 下一个);Console.WriteLine(res);

输出:

,一,二,三

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

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

更多信息 - MSDN:聚合查询

<小时>

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

 var res = words.Aggregate(新的 StringBuilder(),(当前,下一个)=>current.Append(current.Length == 0? "" : ", ").Append(next)).ToString();

What is the most efficient way to write the old-school:

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

...in LINQ?

解决方案

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

This outputs:

, one, two, three

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.

More information - MSDN: Aggregate Queries


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天全站免登陆