【问题标题】:What's the nvelocity/C# equivalent of "if x in array"?“如果 x 在数组中”的 nvelocity/C# 等价物是什么?
【发布时间】:2009-07-27 06:09:14
【问题描述】:

破解 Nvelocity C#/.NET 视图模板(.cs 文件),我真的缺少 Python 关键字“in”(如“foo in list”)。检查列表/数组成员的内置是什么?

这就是我的 Python 大脑想要做的事情:

#set ( $ignore = ['a','b','c'] )
<ul>
#foreach ( $f in $blah )
  #if ( $f not in $ignore )
    <li> $f </li>
  #end
#end
</ul>

但我不确定正确的语法是什么,如果确实有的话。我快速浏览了Velocity Template Guide,但没有发现任何有用的信息。

【问题讨论】:

    标签: c# .net nvelocity


    【解决方案1】:

    你可以在List中使用Contains函数,所以应该是

    List<int> list = new List<int>{1, 2, 3, 4, 5, 6, 7};
    foreach(var f in blah)
    if(list.Contains(f))
    

    【讨论】:

      【解决方案2】:

      “包含”确实是我想要的。

      ...在 NVelocity 模板中说话:

      #set( $ignorefeatures = ["a", "b"] ) 
      #foreach( $f in $blah )
          #if ( !$ignorefeatures.Contains($f.Key) )
              <tr><td> $f.Key </td><td> $f.Value </td></tr>
          #end                
      #end
      

      【讨论】:

        【解决方案3】:
        string[] ignore = {"a", "b", "c" };
        foreach( var item in blah ){
            if( !ignore.Contains(item) )
            {
                // do stuff
            }
        }
        

        【讨论】:

          【解决方案4】:

          如果 "ignore" 是列表,则其上有 Contains() 方法。 这将使您的代码如下所示:

          var ignore = new List<string>();
          ignore.AddRange( new String[] { "a", "b", "c" } );
          foreach (var f in blah) {
              if (!ignore.conains(f)) {
                  //
              }
          }
          

          【讨论】:

            【解决方案5】:

            您可以使用 List.Contains

            请注意,如果您有一个数组,您可以将数组转换为 IList,或者创建一个新的 List 将数组传入。

            【讨论】:

              【解决方案6】:

              不确定您将使用哪个版本的 C#,但如果您有 Linq,那么您可以在数组上使用 Contains。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2011-05-13
                • 1970-01-01
                • 2014-05-08
                • 1970-01-01
                • 2023-03-30
                • 2010-09-17
                • 2011-07-26
                • 2011-01-07
                相关资源
                最近更新 更多