识别循环的第一次迭代,c#

时间:2013-08-22 11:57:36

标签: c# xml loops xmlnode

这是非常基本的,但我想知道是否有更好的方法来编程以下概念。

 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;
                 }

基本上我将c#中的节点输出到表中,我希望每个属性名用逗号分隔。问题是,对于循环的第一个实例,我希望不要在它之前使用逗号,即我不能只有

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

否则单元格中的输出看起来像:

, name, day

而不是

name, day

因此,尽管这样可行,但每次循环时检查计算机的时间似乎是浪费,这确实是循环的第一次迭代,特别是当这个循环嵌套在递归方法中时。有没有更好的方法呢?

(请记住for循环条件中的node.ChildNodes [i] .Attributes.Count可能为0,即node(它是一个xmlNode)可能没有子节点,因此循环加倍为一个存在检查孩子们。)

我希望我能很好地解释这一点!

3 个答案:

答案 0 :(得分:4)

尝试string.Join

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

答案 1 :(得分:2)

使用string.Join方法。这是一个华而不实的方式来完成整个事情:

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

答案 2 :(得分:0)

如果你想用循环来做,请从第二次迭代开始:

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

这是一般的想法