我有一个从WCF服务返回的列表,用于服务器上的文件列表。之后,我将使用它在客户端应用程序中填充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到目前为止,我已经查看了堆叠溢出的帖子:
1 :C# Sort files by natural number ordering in the name? 2:Sorting a FileInfo[] based using Natural Sorting on the filename (SQL files) .
没有人为我的案子工作,任何帮助都将不胜感激:)
发布于 2015-07-21 11:59:01
这是一个方便的列表扩展,用于自然排序:
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);
}
}
}该程序的输出是:
abc.jpg
abc10.jpg
abc97.jpg
abc98.jpg
abc100.jpg
abc101.jpg
abc102.jpg这利用了Windows StrCmpLogicalW()方法的优势,该方法可以进行自然排序顺序比较,并使用P/Invoke调用它。
https://stackoverflow.com/questions/31538293
复制相似问题