问题
I have a List which is being returned from a WCF service ,for List of files on Server. Which i am later using to populate the TreeView in my Client Application
I need the list to be in naturally sorted order.
For ex : I have a list something like
List-1
, and my expected result isList-2
but i getList-3
as my output.(refer list given below)
List-1 List-2 List-3
abc.jpg abc.jpg abc.jpg
abc10.jpg abc10.jpg abc10.jpg
abc100.jpg abc97.jpg abc100.jpg
abc98.jpg abc98.jpg abc101.jpg
abc97.jpg abc100.jpg abc102.jpg
abc102.jpg abc101.jpg abc97.jpg
abc101.jpg abc102.jpg abc98.jpg
So far i have looked into the stackoverflow's post :
[1] :C# Sort files by natural number ordering in the name? [2]: Sorting a FileInfo[] based using Natural Sorting on the filename (SQL files) .
None of them found to working for my case , Any help would be appreciated :)
回答1:
Here you go; a handy list extension for natural sorting:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Demo
{
// A List extension class for natural sorting.
public static class ListExt
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string lhs, string rhs);
// Version for lists of any type.
public static void SortNatural<T>(this List<T> self, Func<T, string> stringSelector)
{
self.Sort((lhs, rhs) => StrCmpLogicalW(stringSelector(lhs), stringSelector(rhs)));
}
// Simpler version for List<string>
public static void SortNatural(this List<string> self)
{
self.Sort(StrCmpLogicalW);
}
}
// Demonstrate using the List extension.
public class Program
{
private static void Main(string[] args)
{
var names = new List<FileInfo>
{
new FileInfo("abc.jpg"),
new FileInfo("abc10.jpg"),
new FileInfo("abc100.jpg"),
new FileInfo("abc98.jpg"),
new FileInfo("abc97.jpg"),
new FileInfo("abc102.jpg"),
new FileInfo("abc101.jpg")
};
names.SortNatural(x => x.Name);
foreach (var name in names)
Console.WriteLine(name);
}
}
}
The output from this program is:
abc.jpg
abc10.jpg
abc97.jpg
abc98.jpg
abc100.jpg
abc101.jpg
abc102.jpg
This takes advantage of the Windows API StrCmpLogicalW() method which does a natural sort order comparison, and uses P/Invoke to call it.
来源:https://stackoverflow.com/questions/31538293/sorting-listfileinfo-in-natural-sorted-order