Anyone have a good resource or provide a sample of a natural order sort in C# for an FileInfo
array? I am implementing the IComparer
interface in my sorts.
相关问题
- Sorting 3 numbers without branching [closed]
- How to toggle on Order in ReactJS
- Graphics.DrawImage() - Throws out of memory except
- PHP Recursively File Folder Scan Sorted by Modific
- Why am I getting UnauthorizedAccessException on th
Matthews Horsleys answer is the fastest method which doesn't change behaviour depending on which version of windows your program is running on. However, it can be even faster by creating the regex once, and using RegexOptions.Compiled. I also added the option of inserting a string comparer so you can ignore case if needed, and improved readability a bit.
Use by
This takes 450ms to sort 100,000 strings compared to 300ms for the default .net string comparison - pretty fast!
Here's a relatively simple example that doesn't use P/Invoke and avoids any allocation during execution.
It doesn't ignore leading zeroes, so
01
comes after2
.Corresponding unit test:
You do need to be careful -- I vaguely recall reading that StrCmpLogicalW, or something like it, was not strictly transitive, and I have observed .NET's sort methods to sometimes get stuck in infinite loops if the comparison function breaks that rule.
A transitive comparison will always report that a < c if a < b and b < c. There exists a function that does a natural sort order comparison that does not always meet that criterion, but I can't recall whether it is StrCmpLogicalW or something else.
My solution:
Results:
Expanding on a couple of the previous answers and making use of extension methods, I came up with the following that doesn't have the caveats of potential multiple enumerable enumeration, or performance issues concerned with using multiple regex objects, or calling regex needlessly, that being said, it does use ToList(), which can negate the benefits in larger collections.
The selector supports generic typing to allow any delegate to be assigned, the elements in the source collection are mutated by the selector, then converted to strings with ToString().
Pure C# solution for linq orderby:
http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html