按自然排序顺序对List 进行排序。

我有一个从WCF服务返回的List,用于服务器上的文件列表。 我后来用于在我的客户端应用程序中填充TreeView

我需要列表按自然排序顺序排列。

例如:我有一个类似List-1 ,我的预期结果是List-2但我得到List-3作为我的输出。(参见下面的列表)

 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 

到目前为止,我已经查看了stackoverflow的post:

[1]: C#按名称中的自然数排序对文件进行排序? [2]: 使用文件名(SQL文件)上的自然排序对FileInfo []进行排序 。

没有人发现为我的情况工作,任何帮助将不胜感激:)

干得好; 一个方便的自然排序列表扩展:

 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(this List self, Func stringSelector) { self.Sort((lhs, rhs) => StrCmpLogicalW(stringSelector(lhs), stringSelector(rhs))); } // Simpler version for List public static void SortNatural(this List self) { self.Sort(StrCmpLogicalW); } } // Demonstrate using the List extension. public class Program { private static void Main(string[] args) { var names = new List { 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); } } } 

该程序的输出是:

 abc.jpg abc10.jpg abc97.jpg abc98.jpg abc100.jpg abc101.jpg abc102.jpg 

这利用了Windows API StrCmpLogicalW()方法,该方法进行自然排序顺序比较,并使用P / Invoke来调用它。