3

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.

pfctdayelise
  • 5,115
  • 3
  • 32
  • 52

6 Answers6

4

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
  • 2,356
  • 1
  • 16
  • 23
3

"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
  • 5,115
  • 3
  • 32
  • 52
1
string[] ignore = {"a", "b", "c" };
foreach( var item in blah ){
    if( !ignore.Contains(item) )
    {
        // do stuff
    }
}
Paul van Brenk
  • 7,450
  • 2
  • 33
  • 38
0

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
  • 3,631
  • 1
  • 28
  • 36
0

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
  • 18,775
  • 1
  • 33
  • 64
0

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
  • 114,894
  • 38
  • 205
  • 284