How to use LINQ in C++/CLI – in VS 2010/.Net 4.0

You can use the Linq methods that are defined in the System::Linq namespace, but you’ll have to jump through a couple extra hoops.

First, C++/CLI doesn’t support extension methods. However, the extension methods are regular methods defined on various classes in System::Linq, so you can call them directly.

List<int>^ list = gcnew List<int>();
int i = Enumerable::FirstOrDefault(list);

Second, C++/CLI doesn’t support lambda expressions. The only workaround is to declare an actual method, and pass that as a delegate.

ref class Foo
{
public:
    static bool GreaterThanZero(int i) { return i > 0; }

    void Bar()
    {
        List<int>^ list = gcnew List<int>();
        int i = Enumerable::FirstOrDefault(list, gcnew Func<int, bool>(&Foo::GreaterThanZero));
    }
}

Leave a Comment