简体   繁体   中英

Python 'in' operator equivalent in C# (.NET 2.0)

I love pythons in-operator and I would like to write it and use it in a c# project. I only have access to .NET Framework 2.0 . I am using the code below but I don't understand the compile error.

using System;
using System.Collections.Generic;
using System.Text;

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

    return sequence.Contains(item);
}

I also have a reference to System as well, but I get the following compile error:

'System.Collections.Generic.IEnumerable<T>' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Collections.Generic.IEnumerable<T>' could be found
(are you missing a using directive or an assembly reference?)

I don't understand what reference I might be missing!

EDIT:

Seems like there is no Linq in .NET framework 2.0. So I downloaded and used the following package: http://www.albahari.com/nutshell/linqbridge.aspx it includes a namespace System.Linq which solves the compile error.

I want to test it with the following code:

char[] x = { 'a', 'b', 'c' };
if('a'.In(x))
{
    ;   
}

But I get confusing errors:

'char' does not contain a definition for 'In' and no extension method 'In' accepting a first argument of type 'char' could be found
(are you missing a using directive or an assembly reference?)

EDIT: A clean built solved the issues.

The Contains static method is defined inside System.Linq .

If you add the line using System.Linq; at the top of your file, your code should compile.

Incidentally, isn't the Contains method identical to Python's 'in' operator? You don't really gain much from creating a custom method, except that you get to type a few less characters/get to reverse the operands.

If you're using .NET 2.0, you might be able to adapt one of the methods in this SO post in lieu of using Linq.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM