Last active
August 29, 2015 14:22
-
-
Save MatthewKing/4b704ad48e3a97d00045 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Adapted from Greg Beech's blog post: | |
// http://gregbee.ch/blog/natural-sort-order-of-strings-and-file | |
// Distributed under the Creative Commons Zero (CC0) license. | |
using System.Collections.Generic; | |
using System.Runtime.InteropServices; | |
using System.Security; | |
/// <summary> | |
/// A string comparer that uses the StrCmpLogicalW function for natural string comparisons. | |
/// </summary> | |
class NaturalStringComparer : IComparer<string> | |
{ | |
/// <summary> | |
/// Contains native methods used by this class. | |
/// </summary> | |
[SuppressUnmanagedCodeSecurity] | |
private static class SafeNativeMethods | |
{ | |
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] | |
public static extern int StrCmpLogicalW(string psz1, string psz2); | |
} | |
/// <summary> | |
/// Gets a default instance of the NaturalStringComparer class. | |
/// </summary> | |
public static NaturalStringComparer Default { get; private set; } | |
/// <summary> | |
/// Initializes static members of the NaturalStringComparer class. | |
/// </summary> | |
static NaturalStringComparer() | |
{ | |
Default = new NaturalStringComparer(); | |
} | |
/// <summary> | |
/// Compares two strings and returns a value indicating whether one is less than, equal to, | |
/// or greater than the other. | |
/// </summary> | |
/// <param name="x">The first string to compare.</param> | |
/// <param name="y">The second string to compare.</param> | |
/// <returns> | |
/// An int that is: zero if x equals y; less than zero if x is less than y; greater than | |
/// zero if x is greater than y. | |
/// </returns> | |
public int Compare(string x, string y) | |
{ | |
return SafeNativeMethods.StrCmpLogicalW(x, y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment