In this post, I will show you how to implement natural sorting in asp.net.There are several ways to implement this, but in this post, I am going to use windows API. Check out the following link for more details
Let’s start the implementation
- Create a new class named
FileList
and add the following code
Create a new class NatualSort.cs add the following code
Here is the complete source code
FileList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class FileList
{
public FileList()
{
}
public string Name { get; set; }
public DateTime DateModified { get; set; }
public string FileType { get; set; }
public static List<FileList> List
{
get
{
return new List<FileList>
{
new FileList{Name="file11.txt",DateModified=DateTime.Now,FileType="Text"},
new FileList{Name="file1.txt",DateModified=DateTime.Now,FileType="Text"},
new FileList{Name="file21.exe",DateModified=DateTime.Now,FileType="Application"},
new FileList{Name="file100.mp3",DateModified=DateTime.Now,FileType="MultiMedia"},
new FileList{Name="file19011.jpg",DateModified=DateTime.Now,FileType="iamge"},
};
}
}
}
NaturalSort.cs
Create a class NaturalSort.cs
and add the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Runtime.InteropServices;
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
}
public sealed class NaturalFileComparer : IComparer<FileList>
{
public int Compare(FileList x, FileList y)
{
return SafeNativeMethods.StrCmpLogicalW(x.Name, y.Name);
}
}
How to use
void Main()
{
var list = FileList.List;
list.Sort(new NaturalFileComparer());
Console.WriteLine(list);
}