Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 !
   }
}

like image 835
bricx Avatar asked Oct 17 '25 15:10

bricx


1 Answers

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

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

//or

List<string> mylist = ((string[])pyList).ToList<string>();
like image 117
bricx Avatar answered Oct 19 '25 06:10

bricx