views:

196

answers:

1

For natural sorting in my application I currently P/Invoke a function called StrCmpLogicalW in shlwapi.dll. I was thinking about trying to run my application under Mono, but then of course I can't have this P/Invoke stuff (as far as I know anyways).

Is it possible to see the implementation of that method somewhere, or is there a good, clean and efficient C# snippet which does the same thing?

My code currently looks like this:

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public class NaturalStringComparer : IComparer<string>
{
    private readonly int modifier = 1;

    public NaturalStringComparer() : this(false) {}
    public NaturalStringComparer(bool descending)
    {
        if (descending) modifier = -1;
    }

    public int Compare(string a, string b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a ?? "", b ?? "") * modifier;
    }
}

So, what I'm looking for is an alternative to the above class which doesn't use an extern function.

A: 

I just found this blog post on natural sorting in C#.

Is this of any use?

In response to your comment - I didn't analyse it in great detail myself, it just looked promising. There must be other c# implementations of natural sorting out there, perhaps you just need to find one and profile it?

ChrisF
Just finished reading it actually :P It seemed to do what I think it should, but it also seems quite inefficient... I don't really know though... hehe.
Svish