Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's 'in' operator equivalent to C#

With Python, I can use 'in' operator for set operation as follows :

x = ['a','b','c']
if 'a' in x:
  do something

What's the equivalent in C#?

like image 746
prosseek Avatar asked Feb 15 '11 21:02

prosseek


1 Answers

Most collections declare a Contains method (e.g. through the ICollection<T> interface), but there's always the more general-purpose LINQ Enumerable.Contains method:

char[] x = { 'a', 'b', 'c' };

if(x.Contains('a'))
{
   ...    
}

If you think that's the 'wrong way around', you could write an extension that rectifies things:

public static bool In<T>(this T item, IEnumerable<T> sequence)
{
   if(sequence == null)
      throw new ArgumentNullException("sequence");

   return sequence.Contains(item);    
}

And use it as:

char[] x = { 'a', 'b', 'c' };

if('a'.In(x))
{
   ...    
}
like image 56
Ani Avatar answered Oct 27 '22 04:10

Ani