Sorting is a common task which I should complete during my development. Sometimes it is very simple, sometimes it is very complicated according to the object which I want to sort. In this small post, I would like to make a simple example of sorting a list of file name to its extension. I will use 2 methods to sort this list: one with class implementing IComparer and one with LINQ.
The list of file names is initialized through hard-code as following
List<string> lstFile = new List<string>() {"1.png","180.PDF","Arial.ttf","BESTÄTIGUNGdoc.doc", "configuration.php", "config.php", "crossdomain.xml", "Daten.mdb", "ebook.chm", "export.swf" };
You can see that the list contains 10 items in random order. To sort them according to its extension I use 2 methods below
1. Implement IComparer<>
Using this method, I need to create a class which implements interface IComparer and its methods.
class ExtensionSorter : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { string strExt1 = Path.GetExtension(x); string strExt2 = Path.GetExtension(y); if (strExt1.Equals(strExt2)) { return x.CompareTo(y); } else { return strExt1.CompareTo(strExt2); } } #endregion }
As you can see because I am going to sort which string-object I can reuse the CompareTo function of string-class to compare. Then pass an instance of this class to Sort() method to sort our list
lstFile.Sort(new ExtensionSorter()); foreach (string strTemp in lstFile) { Console.WriteLine(strTemp); }
The output looks like the image below
2. Use LINQ
LINQ is only available from .NET framework 3.0 but in this post http://hintdesk.com/c-use-linq-on-net-framework-2-0/ I showed you how we can use it with .NET framework 2.0 and hence I can sort the list very fast when using LINQ without creating any class.
var vSort = from s in lstFile orderby Path.GetExtension(s), s ascending select s; foreach (string strTemp in vSort) { Console.WriteLine(strTemp); }
The result is completely same with the output from first method
The advantage of LINQ in compare to IComparer<> is that we can use SQL Statement to make a sort algorithm on a simple object without creating any helper class. The complete source code of this example you can download here “Sort To File Extension“