Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join a string[] Without Using string.Join

Tags:

string

c#

.net

linq

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!

like image 428
Mike Perrenoud Avatar asked Oct 03 '12 18:10

Mike Perrenoud


1 Answers

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.

like image 165
Thom Smith Avatar answered Sep 26 '22 23:09

Thom Smith