Question

This is very basic but i was wondering if there was a better way of programming the following concept.

 for (int j = 0; j < node.ChildNodes[i].Attributes.Count; j++)
                {
                    if (j != 0) row.Cells[1].Value += ", ";
                    row.Cells[1].Value += node.ChildNodes[i].Attributes[j].Name;
                 }

Basically im outputting nodes in c# to a table and i want each attribute name to be separated with a comma. The issue is that obviously for the first instance of the loop i wish not to have the comma preceded it, ie i could not just have

row.Cells[1].Value +=  ", " + node.ChildNodes[i].Attributes[j].Name;

otherwise the output in the cell would look something like:

, name, day

instead of

name, day

So although this works, it seems a waste of the computer time to check each time it loops that this is indeed the first iteration of the loop, especially as this loop is nested in a recursive method. Is there a better way of doing this?

(Bearing in mind that node.ChildNodes[i].Attributes.Count in the for loop conditions may be 0, ie node(which is a xmlNode) could have no child nodes, so the the loop doubles up as an existence check for the children too. )

I hope i explained this well!

Was it helpful?

Solution

Try string.Join

var commaSeperated = string.Join(", ", node.ChildNodes[i].Attributes.Select(a => a.Name));

OTHER TIPS

Use the string.Join method. Here's a flashy way to do the whole thing in a single line:

row.Cells[1].Value = string.Join(", ", node.ChildNodes
    .SelectMany(node => node.Attributes.Select(attribute => attribute.Name)))

If you want to do it with a loop, start with the second iteration:

string result = array[0];
for(int i = 1; i < array.Length; i++)
    result += ", " + array[i];

that's the general idea

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top