Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Join a string[] Without Using string.Join

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!

Upvotes: 6

Views: 292

Answers (5)

Filix Mogilevsky
Filix Mogilevsky

Reputation: 777

string myString = "Hello World"
var myList= new List<int>();

for (int i = 0; i < 10; i++)
    myList.Add(i);

var newList = myList.Aggregate(string.Empty, (current, num) => current + myString.Substring(num, 1));

Upvotes: 0

Guffa
Guffa

Reputation: 700402

Don't use Split either, just locate the last comma and use Substring to divide the string:

int pos = line.LastIndexOf(',');
var elem = new XElement("shop");
elem.SetAttributeValue("name", line.Substring(0, pos).Replace(",", String.Empty));
elem.SetAttributeValue("tin", line.Substring(pos + 1));

Upvotes: 4

Thom Smith
Thom Smith

Reputation: 14086

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.

Upvotes: 6

YoryeNathan
YoryeNathan

Reputation: 14522

var strs = new string[100];
...

var result = strs.Aggregate(new StringBuilder(strs.Sum(x => x.Length)),
                            (sb, curr) => sb.Append(s + ", ")).ToString();

Just need to remove the last ", " from the end now.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152566

how about

split.Take(split.Length - 1).Aggregate((s1,s2)=> s1 + s2);

or the non-linq equivalent:

string s = "";
for(int i = 0; i < split.Length - 1; i++)
{
   s += split[i];
}
return s;

Upvotes: 2

Related Questions