tags:

views:

377

answers:

6

Hacking on a Nvelocity C#/.NET view template (.cs file), I'm really missing the Python keyword "in" (as in, "foo in list"). What is the built-in for checking list/array membership?

This is what my Python brain wants to do:

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

But I am not sure what the right syntax is, if there is indeed any. I had a quick look at the Velocity Template Guide but didn't spot anything useful.

+1  A: 
string[] ignore = {"a", "b", "c" };
foreach( var item in blah ){
    if( !ignore.Contains(item) )
    {
        // do stuff
    }
}
pb
+4  A: 

You can use the Contains function in List, so it should be

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

If "ignore" is list, there is Contains() method on it. That would make your code something like this:

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

You can utilize List.Contains

Note that if you have an array you can cast the array to IList, or create a new List passing the array in.

Guvante
A: 

Not sure what version of C# you'd be using, but if you have Linq then you can use Contains on an array.

Daniel Earwicker
Even on any enumerable ;)
Oliver Hanappi
+2  A: 

"Contains" is indeed what I was looking for.

...And in NVelocity template-speak:

#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
pfctdayelise