Last active
August 29, 2015 13:58
-
-
Save kjlape/10049467 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| using System; | |
| using System.Linq; | |
| using System.Text.RegularExpressions; | |
| using System.Collections.Generic; | |
| using System.Globalization; | |
| namespace MyNamespace | |
| { | |
| public class HumanStringWithNumbersComparer : StringComparer | |
| { | |
| public HumanStringWithNumbersComparer(CultureInfo culture = null, CompareOptions options = CompareOptions.None) | |
| { | |
| _culture = culture ?? CultureInfo.InvariantCulture; | |
| _options = options; | |
| } | |
| #region implemented abstract members of StringComparer | |
| public override int Compare(string a, string b) | |
| { | |
| return MatchCollectionToStrings(_regex.Matches(a)) | |
| .Zip(MatchCollectionToStrings(_regex.Matches(b)), | |
| (x, y) => | |
| { | |
| int rx, ry; | |
| if (int.TryParse(x, out rx) && int.TryParse(y, out ry)) | |
| return rx.CompareTo(ry); | |
| else | |
| return string.Compare(x, y, _culture, _options); | |
| }) | |
| .FirstOrDefault(x => x != 0); | |
| } | |
| public override bool Equals(string x, string y) | |
| { | |
| return x == y; | |
| } | |
| public override int GetHashCode(string obj) | |
| { | |
| return obj.GetHashCode(); | |
| } | |
| #endregion | |
| IEnumerable<string> MatchCollectionToStrings(MatchCollection matches) | |
| { | |
| return matches.Cast<Match>() | |
| .Select(x => x.Value); | |
| } | |
| readonly Regex _regex = new Regex(@"(\D+|\d+)"); | |
| readonly CultureInfo _culture; | |
| readonly CompareOptions _options; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment