简体   繁体   English

如何使用 foreach 循环在列表中的短语之间添加分隔符?

[英]How can I add a delimiter between phrases in a list with foreach loop?

I have this code:我有这个代码:

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

The InnerText is simply 1-2 characters that never contain the # symbol. InnerText只是 1-2 个字符,从不包含#符号。 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 .结果将是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.如果我只是简单地添加# ,那么我会得到ab#cd# ,这不是我想要的。

Using the string.Join is a good place to use in this situation.使用string.Join是在这种情况下使用的好地方。

string result = string.Join("#", nodes.Select(n => n.InnerText))

You can use .IndexOf to know the current index of node in foreach loop.您可以使用.IndexOf了解foreach循环中节点的当前索引。 You should be concatenating node.InnerText as long as current index of node is not equal to (nodes.Count - 1) .只要节点的当前索引不等于(nodes.Count - 1) ,您就应该连接node.InnerText

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM