OrderBy Object Sorting

I was determined to find a way to sort an array or list of objects easily. Of course most people are familiar with the standard “.sort” method that you pass a comparison object that inherits from IComparable as follows:

  1. public class FilesDateComparer: IComparer
  2. {
  3. public int Compare (object x, object y)
  4. {
  5.  
  6. int iResult;
  7.  
  8. FileInfo oFileX=(FileInfo)x;<ol>
  9.  
  10. FileInfo oFileY=(FileInfo)y;
  11.  
  12. if(oFileX.LastWriteTime==oFileY.LastWriteTime)
  13. {
  14. iResult=0;
  15. }
  16. else
  17. if(oFileX.LastWriteTime>oFileY.LastWriteTime)
  18. {
  19. iResult=1;
  20. }
  21. else
  22. {
  23. iResult=-1;
  24. }
  25. return iResult;
  26. }
  27. }

This seems so tedious to have to create a custom sort class for a one time sort operation (probably a bit of laziness too…). Thats when I came across some nice Linq extensions code that is in the .NET Framework 3.0+. It definitely makes things quite a bit easier. Take a look at this example showing how to easily sort files by date:

  1. foreach(FileInfo info in dir.GetFiles().OrderBy(f=>f.LastWriteTime).ToArray())
  2. {
  3. // do some operation
  4. }

The order by method accepts a Linq expression, f representing the object we are referring too. Even works with the objects intellisense. Well done Microsoft. Alternatively, you can sort decescending using the OrderByDescending method exactly the same:

  1. foreach(FileInfo info in dir.GetFiles().OrderByDescending(f=>f.LastWriteTime).ToArray())
  2. {
  3. // do some operation
  4. }

Leave a Reply