2016-03-22 174 views
0

我有MyCustomMacro返回字符串列表。 我需要使用自定義分隔符beetwen列表元素來顯示此列表。獲取Foreach中的項目索引

{% 
foreach (ev in MyCustomMacro("events")) 
{ 
    ev + " | "; 
}; 
#%} 

但是這段代碼還在最後一個元素後加「|」。

如何檢查該元素是否在列表中的最後?

+1

的[你怎麼foreach循環的當前迭代的指標?(可能的複製http://stackoverflow.com/questions/43021/how-do-you-get-the-index -of-the-current-ite-of-a-foreach-loop) – Bryan

回答

-1

您可以使用加入字符串類的方法:

{%string.join(「|」,MyCustomMacro(「events」)) )%}

+0

這段代碼只在Kentico CMS中工作,它是一個K#宏表達式。在C#中,你只需要使用'string.join(「|」,新字符串[] {})'' –

0

您可以通過此做伊斯利:

{% result=""; 
    foreach (ev in MyCustomMacro("events")) 
    { 
    result+= ev + " | "; 
    }; 
    result.TrimEnd(" | ") 
%} 
+0

這起作用,但有點破解。使用一個已經爲此創建的方法,例如'string.Join()' –

3

如果你能得到一個字符串數組中的值,你可以這樣做:

string.Join("|", events[]) 

Examples

2

我想一個很有效的方法是使用字符串StringBuilder類。

東西在這些線上。

{% 
    var builder = new StringBuilder(); 
    foreach (ev in MyCustomMacro("events")) 
    { 
    builder.append(ev + " | "); 
    }; 
    result = String.Join("|", builder.Split('|')); 
%}