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#?
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))
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With