2

I have a Dictionary which Values i wanted to transform into a List. In C# I would use this approach:

var dict = new Dictionary<int, int>();
var list = dict.Values.ToList();

So I wanted to do the same in C++/CLI:

auto dict = gcnew Dictionary<int, int>();
auto list = dict->Values->ToList(); // error C2039

But this doesn't work, because of the error:

Error   C2039   
'ToList': is not a member of 'System::Collections::Generic::Dictionary<int,int>::ValueCollection'   

I don't know, what I am doing wrong, I am new to C++/CLI.

Minimal reproducable example:

#using "System.Linq.dll"

using namespace System::Collections::Generic;
using namespace System::Linq;

int main()
{
    auto dict = gcnew Dictionary<int, int>();
    auto list = dict->Values->ToList();
}

Compiled with:

cl /clr test.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27035
for Microsoft (R) .NET Framework version 4.08.4121.0
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
test.cpp(10): error C2039: 'ToList': is not a member of 'System::Collections::Generic::Dictionary<int,int>::ValueCollection'
RoQuOTriX
  • 2,871
  • 14
  • 25
  • 1
    Have you imported namespace `Linq` into `C++` sample: `using namespace System::Linq`? – Iliar Turdushev May 13 '20 at 06:21
  • @IliarTurdushev Yes – RoQuOTriX May 13 '20 at 06:23
  • 1
    It seems that `C++ CLI` does not support calling extension methods using syntax `obj.ExtMethod(args)`: https://stackoverflow.com/questions/5643734/how-to-use-linq-in-c-cli-in-vs-2010-net-4-0/5645267#5645267. You should call `ToList` as regular static method: `Linq::Enumerable::ToList(list);`. – Iliar Turdushev May 13 '20 at 06:33
  • @IliarTurdushev I provided a compilable example which shows the error. Your comment should be an answer ;) but maybe my question is a duplicate – RoQuOTriX May 13 '20 at 06:37

1 Answers1

2

C++ CLI does not support calling extension methods as members of target type:

targetType.ExtensionMethod(args);

You should call ToList() as a regular static method:

Linq::Enumerable::ToList(list);
Iliar Turdushev
  • 4,935
  • 1
  • 10
  • 23