This question is for academic purposes only.
Let's assume I have the following code ...
var split = line.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
var elem = new XElement("shop");
elem.SetAttributeValue("name", split.Take(split.Length - 1)); <=====
elem.SetAttributeValue("tin", split.Last());
And I would like the line with the arrow to produce the same result as this ...
string.Join(string.Empty, split.Take(split.Length - 1));
... without using string.Join
.
Is that possible? I can't seem to find a LINQ statement to do it ... hopefully y'all already know!
Using a StringBuilder
for O(n) performance:
split
.Take(split.Length - 1)
.Aggregate(new StringBuilder(), (sb, s) => sb.Append(s)).ToString();
If the object is to avoid the awkwardness of a tree of combined LINQ calls and static methods, then a straightforward solution is an extension method:
public static string Join(this IEnumerable<string> self, string separator = "")
{
return string.Join(separator, self);
}
And then:
split.Take(split.Length - 1).Join();
I find this to read much better than using string.Join
in complicated expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With