Attach string [] Without using string.Join

This question is for academic purposes only.

Suppose 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 it possible? I can't seem to find a LINQ instruction for this ... hope you already know!

+6
source share
5 answers

Do not use Split , just find the last comma and use Substring to split the line:

 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)); 
+4
source

Using StringBuilder performance for O (n):

 split .Take(split.Length - 1) .Aggregate(new StringBuilder(), (sb, s) => sb.Append(s)).ToString(); 

If an object should avoid the awkwardness of the tree of combined LINQ calls and static methods, then an extension method is a simple solution:

 public static string Join(this IEnumerable<string> self, string separator = "") { return string.Join(separator, self); } 

And then:

 split.Take(split.Length - 1).Join(); 

I believe this is much better than using string.Join in complex expressions.

+6
source

What about

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

or the equivalent of non-linq:

 string s = ""; for(int i = 0; i < split.Length - 1; i++) { s += split[i]; } return s; 
+2
source
 var strs = new string[100]; ... var result = strs.Aggregate(new StringBuilder(strs.Sum(x => x.Length)), (sb, curr) => sb.Append(s + ", ")).ToString(); 

You just need to remove the last "," from the very end.

0
source
 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)); 
0
source

Source: https://habr.com/ru/post/926875/


All Articles