Sorting List<FileInfo> in Natural sorted order .

只愿长相守 提交于 2019-11-28 02:24:40

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!