0

I have this code:

foreach (var node in nodes)
{
    result += node.InnerText;
}

The InnerText is simply 1-2 characters that never contain the # symbol. There can be one or more values of node in nodes.

How can I delimit each of these so that, for example, if these were the values of node:

"ab" and "cd"  

That the result would be ab#cd.

I know I can just add # to the value but then what about the last character. If I just did simple adding of # then I would get ab#cd# which is not what I want.

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • You have a couple of options, 1) check if you're on the first item, and if not, add the delimiter *before* adding the item, or 2) use `string.Join("#", collection)` but then you need to prepare a collection of the individual elements – Lasse V. Karlsen Oct 03 '19 at 06:55
  • String.Join, take a delimeter and a enumerable string so. `result = String.join("#", nodes.Select(x=> x.InnerText))` – xdtTransform Oct 03 '19 at 06:56
  • 1
    Possible duplicate of [C# List to string with delimiter](https://stackoverflow.com/questions/3575029/c-sharp-liststring-to-string-with-delimiter) – xdtTransform Oct 03 '19 at 06:57
  • related https://stackoverflow.com/questions/581448/join-a-string-using-delimiters – xdtTransform Oct 03 '19 at 06:58

2 Answers2

5

Using the string.Join is a good place to use in this situation.

string result = string.Join("#", nodes.Select(n => n.InnerText))
Johnny
  • 8,939
  • 2
  • 28
  • 33
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
-1

You can use .IndexOf to know the current index of node in foreach loop. You should be concatenating node.InnerText as long as current index of node is not equal to (nodes.Count - 1).

foreach (var node in nodes)
{
    //You can identify the last element in nodes like below
    if (nodes.IndexOf(node) != nodes.Count - 1) 
    {
        result += node.InnerText;
    }
}
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
  • Why downvotes? Please care to explain. I just gave another way of doing it. – Rahul Nikate Oct 03 '19 at 06:59
  • Possible reason are too many: Answering a clear dupe. String concatenation in a tight loop, code only. I don't like the voting pattern on those question in a more general way, i don't get the downvote or the down votes here – xdtTransform Oct 03 '19 at 07:01
  • @xdtTransform I just posted my answer very quickly and thought to update in next few minutes. Anyway your comment is fair enough. I'm agree with you. I should have chose to mark question as a duplicate. – Rahul Nikate Oct 03 '19 at 07:07