Search code examples
sortingvala

how to sort a list in Vala using custom Comparator


I'm trying to get a directory listing and sort it into last modified time order using Vala.

I've got the directory listing part into a List < FileInfo >. But I cannot figure out how to sort the list.


Solution

  • This is done via the the sort(CompareFunc<G> compare_func) method in the List class. You can read more about it here.

    A basic example for strings would be:

    list.sort((a,b) => {
        return a.ascii_casecmp(b);
    });
    

    The return value of the function passed to sort() is the same as the ISO C90 qsort(3) function:

    The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

    As you're interested in modify time, the FileAttribute you're looking for is TIME_MODIFIED which you would get by calling the appropriate get_attribute_* method of FileInfo.