Vala: convert List to array


Vala noob here :slight_smile:

C# has a ToArray() method to convert a List<T> to array T[], is there anything similar in Vala?

I made that code below, but I find it quite ugly (resizing in loop…), has anyone a better way for converting?

private bool on_drop (Gtk.DropTarget dt, Value val, double x, double y)
    Gdk.FileList flist = val as Gdk.FileList;

    if (null == flist)
        return false;

    /* FIXME: is there a better way to convert GLib.SList to array? */
    GLib.File[] files = new GLib.File[0];
    foreach (GLib.File f in flist.get_files())
        files += f;

    this.open_files(files);   // takes an array, because it's also called by

    return true;

Your solution doesn’t look wrong. There is no existing method to turn a List into an array. You could of course not demand an array, but a List or FileList by open_files. Also there is Gtk.DirectoryList, maybe that works for you better.

1 Like

If I’m not mistaken, Vala allocates array memory in chunks of 128 bytes. So, you might just be fine. You can check the generated C code to confirm if it is true or not.

I have a generic implementation of this but that isn’t better either.

1 Like

OK, thanks!

Yeah I could pass a FileList or SList<File> to open_files but then I need to adapt the open handler of my GApplication to convert the array it receives to whatever open_files accepts (I would like to open files by both commandline and drag-n-drop). If there was a ToArray() method things would have been easier :slight_smile:

I think the Gtk.DirectoryList doesn’t suit well for my usecase. But could be super useful to open a folder and track its content. Thanks for the hint anyway!

Ah, interesting indeed.
Thanks for the link!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.