Python.NET - convert Python List to .NET List (C#)

Viewed 1596

I am importing a python list (of string) in C# using Python.NET and I can't find any example of conversion from Python.NET dynamic object to C# List (all examples out there seems to be in the opposite direction C# to Python).

I tried to cast the dynamic python.net object with (List<string>) and with Enumerable.ToList<string>() but both failed. The as operator returned null. The only thing that worked was to loop over it with foreach... but is this really the only way and the best solution ?

Here is the code:

using (Py.GIL())
{
   dynamic MyPythonClass = Py.Import("MyPythonClass")
   dynamic pyList = MyPythonClass.MyList;
   
   //List<string> mylist = (List<string>)pyList;               //failed
   //List<string> mylist = Enumerable.ToList<string>(pyList);  //failed
   //List<string> mylist = pyList as List<string>;             //returns null

   List<string> mylist = new List<string>();
   foreach(string item in pyList)
   {
         mylist.Add(item);                                     //Success !
   }
}

1 Answers

Answer was (shamefully) very simple, thanks to @Dave:

string[] mylist = (string[])pyList;

//or

List<string> mylist = ((string[])pyList).ToList<string>();
Related