Reputation: 3512
As I know string are immutable in C# unless StringBuilder class is used. The situation is, I have an ObjectResult(which implements IEnumerable) of string and I want to convert it to one single string object. There are two options here:
using string.Concat
var myDesiredData = string.Concat(TheObjectResult)
using StringBuilder
var sb = new StringBuiler();
foreach (var item in TheObjectResult)
{
sb.Append(item);
}
var myDesiredData = sb.ToString();
I'm not sure how the first option is working.
Upvotes: 1
Views: 625
Reputation: 3925
Both options are almost identical. This is how string.Concat(IEnumerable<string>)
is implemented:
[ComVisible(false)]
public static String Concat(IEnumerable<String> values) {
if (values == null)
throw new ArgumentNullException("values");
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
StringBuilder result = StringBuilderCache.Acquire();
using(IEnumerator<String> en = values.GetEnumerator()) {
while (en.MoveNext()) {
if (en.Current != null) {
result.Append(en.Current);
}
}
}
return StringBuilderCache.GetStringAndRelease(result);
}
I would go with string.Concat
, because why write a method that already exists.
Upvotes: 6