开发者

Python's 'in' operator equivalent to C#

With Python, I can use 'in' operator for set o开发者_Python百科peration as follows :

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

What's the equivalent in C#?


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))
{
   ...    
}


To build on Ani's answer, Python's in operator for dictionaries is the equivalent of ContainsKey in C#, so you would need two extension methods:

public static bool In<T, V>(this T item, IDictionary<T, V> sequence)
{
    if (sequence == null) throw new ArgumentNullException("sequence");
    return sequence.ContainsKey(item);
}

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜