I have a directory with 40 files with names from 0 to 39 (for example), I am trying to get the file with the largest number in its name (which means I need to get "39") I am trying to sort the directory.. I have tried using the following topics:
How to retrieve list of files in directory, sorted by name
Sorting the result of Directory.GetFiles in C#
Nothing works for me.. I tried each of the methods - using Linq and the others.. and I dunno why..
I get the following result of the sorting (check picture below):
Thanks for the help,
Din Bracha.
It is only logical that they would be sorted that way, you would bring in some semantics to sort it by number, namely parse all the file names to numbers, then sort the files by that.
Something like
files.OrderBy(path => Int32.Parse(Path.GetFileNameWithoutExtension(path)))
Use Last()
to get the file with the highest number.
There is a native function in windows StrCmpLogicalW
that will compare in strings numbers as numbers instead of letters. It is easy to make a comparer that calls out to that function and uses it for it's comparisons.
public class StrCmpLogicalComparer : Comparer<string>
{
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
public override int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
}
Here is a example program that will show the diffrence between the default sort and the StrCmpLogicalW
sort
class Program
{
static void Main()
{
List<string> items = new List<string>()
{
"Example1.txt", "Example2.txt", "Example3.txt", "Example4.txt", "Example5.txt", "Example6.txt", "Example7.txt", "Example8.txt", "Example9.txt", "Example10.txt",
"Example11.txt", "Example12.txt", "Example13.txt", "Example14.txt", "Example15.txt", "Example16.txt", "Example17.txt", "Example18.txt", "Example19.txt", "Example20.txt"
};
items.Sort();
foreach (var item in items)
{
Console.WriteLine(item);
}
Console.WriteLine();
items.Sort(new StrCmpLogicalComparer());
foreach (var item in items)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
which outputs
Example1.txt
Example10.txt
Example11.txt
Example12.txt
Example13.txt
Example14.txt
Example15.txt
Example16.txt
Example17.txt
Example18.txt
Example19.txt
Example2.txt
Example20.txt
Example3.txt
Example4.txt
Example5.txt
Example6.txt
Example7.txt
Example8.txt
Example9.txt
Example1.txt
Example2.txt
Example3.txt
Example4.txt
Example5.txt
Example6.txt
Example7.txt
Example8.txt
Example9.txt
Example10.txt
Example11.txt
Example12.txt
Example13.txt
Example14.txt
Example15.txt
Example16.txt
Example17.txt
Example18.txt
Example19.txt
Example20.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With