Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a List<FileInfo> by creation date C#

Using this example off MSDN:

using System.Collections.Generic;  
using System.IO;  

namespace CollectionTest  
{  
    public class ListSort  
    {  
        static void Main(string[] args)  
        {  
            List<FileInfo> files = new List<FileInfo>();  
            files.Add(new FileInfo("d(1)"));  
            files.Add(new FileInfo("d"));              
            files.Add(new FileInfo("d(2)"));  

            files.Sort(new CompareFileInfoEntries());  
        }           

    }  

    public class CompareFileInfoEntries : IComparer<FileInfo> 
    {  
        public int Compare(FileInfo f1, FileInfo f2)  
        {  
            return (string.Compare(f1.Name, f2.Name));  
        }  
    }  

}  

How would I compare the date of creation.

F1 has a property "creation" date which is a FileSystemInfo.Datetime, yet when I try this:

  public class CompareFileInfoEntries : IComparer<FileInfo>
  {
      public int Compare(FileInfo f1, FileInfo f2)
      {

          return (DateTime.Compare(DateTime.Parse(f1.CreationTime), f2.CreationTime));
      }
  }  
}

I get overload method matches for String. compare(string,string) Note: Ive used two methods in the above script to attempt returning the creation time. Neither have worked - they would both be the same in my actual script.

CLosest I can get is:

return (DateTime.Compare(DateTime.Parse(f1.CreationTime.ToString()), DateTime.Parse(f2.CreationTime.ToString() )));
like image 769
JustAnotherDeveloper Avatar asked Jan 25 '12 10:01

JustAnotherDeveloper


2 Answers

Description

You can simple use LINQ (namespace System.Linq) for that.

Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages

Sample

List<FileInfo> orderedList = files.OrderBy(x => x.CreationTime).ToList();

More Information

  • MSDN - Enumerable.OrderBy
  • Wikipedia - Language Integrated Query
like image 41
dknaack Avatar answered Oct 06 '22 11:10

dknaack


Umm what about using linq

files.OrderBy(f=>f.CreationTime)
like image 113
Not loved Avatar answered Oct 06 '22 11:10

Not loved