C# 使用 LINQ 连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/217805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using LINQ to concatenate strings
提问by tags2k
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?
...在 LINQ 中?
采纳答案by Jorge Ferreira
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
此答案显示Aggregate
了问题中要求的 LINQ ( )用法,并不适合日常使用。因为这不使用 aStringBuilder
它会在很长的序列中产生可怕的性能。对于常规代码使用String.Join
,如其他答案所示
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 IEnumerableobject.
聚合是一个函数,它接受一组值并返回一个标量值。T-SQL 中的示例包括 min、max 和 sum。VB 和 C# 都支持聚合。VB 和 C# 都支持聚合作为扩展方法。使用点符号,可以简单地调用IEnumerable对象上的方法。
Remember that aggregate queries are executed immediately.
请记住,聚合查询是立即执行的。
More information - MSDN: Aggregate Queries
更多信息 - MSDN:聚合查询
If you really want to use Aggregate
use variant using StringBuilder
proposed in comment by CodeMonkeyKingwhich would be about the same code as regular String.Join
including good performance for large number of objects:
如果您真的想使用CodeMonkeyKing在评论中提出的Aggregate
使用变体StringBuilder
,这将与常规代码大致相同,包括对大量对象的良好性能:String.Join
var res = words.Aggregate(
new StringBuilder(),
(current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
.ToString();
回答by Robert S.
Have you looked at the Aggregate extension method?
你看过聚合扩展方法吗?
var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);
回答by Armin Ronacher
Why use Linq?
为什么要使用 Linq?
string[] s = {"foo", "bar", "baz"};
Console.WriteLine(String.Join(", ", s));
That works perfectly and accepts any IEnumerable<string>
as far as I remember. No need Aggregate
anything here which is a lot slower.
IEnumerable<string>
据我所知,这非常有效并且可以接受任何内容。Aggregate
这里不需要任何东西,这会慢很多。
回答by Daniel Earwicker
Real example from my code:
我的代码中的真实示例:
return selected.Select(query => query.Name).Aggregate((a, b) => a + ", " + b);
A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.
查询是一个对象,它有一个 Name 属性,它是一个字符串,我想要所选列表中所有查询的名称,用逗号分隔。
回答by Jon Skeet
There are various alternative answers at this previous question- which admittedly was targeting an integer array as the source, but received generalised answers.
上一个问题有各种替代答案- 诚然,这些答案是针对整数数组作为源,但收到了概括性的答案。
回答by Amy B
回答by Kieran Benton
I always use the extension method:
我总是使用扩展方法:
public static string JoinAsString<T>(this IEnumerable<T> input, string seperator)
{
var ar = input.Select(i => i.ToString()).ToArray();
return string.Join(seperator, ar);
}
回答by Patrik H?gne
I blogged about this a while ago, what I did seams to be exactly what you're looking for:
不久前我写了一篇关于这个的博客,我所做的接缝正是你正在寻找的:
http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html
http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html
In the blog post describe how to implement extension methods that works on IEnumerable and are named Concatenate, this will let you write things like:
在博客文章中描述了如何实现适用于 IEnumerable 并命名为 Concatenate 的扩展方法,这将让您编写如下内容:
var sequence = new string[] { "foo", "bar" };
string result = sequence.Concatenate();
Or more elaborate things like:
或者更复杂的事情,例如:
var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);
string result = methodNames.Concatenate(", ");
回答by Kelly
Lots of choices here. You can use LINQ and a StringBuilder so you get the performance too like so:
这里有很多选择。您可以使用 LINQ 和 StringBuilder 来获得这样的性能:
StringBuilder builder = new StringBuilder();
List<string> MyList = new List<string>() {"one","two","three"};
MyList.ForEach(w => builder.Append(builder.Length > 0 ? ", " + w : w));
return builder.ToString();
回答by user337754
quick performance data for the StringBuilder vs Select & Aggregate case over 3000 elements:
超过 3000 个元素的 StringBuilder 与 Select & Aggregate 案例的快速性能数据:
Unit test - Duration (seconds)
LINQ_StringBuilder - 0.0036644
LINQ_Select.Aggregate - 1.8012535
单元测试 - 持续时间(秒)
LINQ_StringBuilder - 0.0036644
LINQ_Select.Aggregate - 1.8012535
[TestMethod()]
public void LINQ_StringBuilder()
{
IList<int> ints = new List<int>();
for (int i = 0; i < 3000;i++ )
{
ints.Add(i);
}
StringBuilder idString = new StringBuilder();
foreach (int id in ints)
{
idString.Append(id + ", ");
}
}
[TestMethod()]
public void LINQ_SELECT()
{
IList<int> ints = new List<int>();
for (int i = 0; i < 3000; i++)
{
ints.Add(i);
}
string ids = ints.Select(query => query.ToString())
.Aggregate((a, b) => a + ", " + b);
}