Sort list <FileInfo> by C # creation date
Using this example with 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 can I compare the creation date.
F1 has a βcreateβ date for the property, which is FileSystemInfo.Datetime, but 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 matching overload labels for String. compare(string,string) String. compare(string,string) Note. Ive used two methods in the above script to try to return the creation time. None of them worked - they would both be the same in my actual script.
I can get:
return (DateTime.Compare(DateTime.Parse(f1.CreationTime.ToString()), DateTime.Parse(f2.CreationTime.ToString() ))); Description
You can simply use LINQ (namespace System.Linq) for this.
Integrated Language Query (LINQ, pronounced βlinkβ) is a component of the Microsoft .NET Framework that adds native query capabilities to data in .NET languages.
Example
List<FileInfo> orderedList = files.OrderBy(x => x.CreationTime).ToList(); Additional Information
Umm how about using linq
files.OrderBy(f=>f.CreationTime) Dim filePath as string = "c:\\" This command retrieves a list of directory files sorted by ASC
Dim orderedFiles = New System.IO.DirectoryInfo(filePath).GetFiles("*.xml") .OrderBy(Function(x) x.CreationTime) This command gets a list of catalog files sorted by DESC
Dim orderedFiles = New System.IO.DirectoryInfo(filePath).GetFiles("*.xml") .OrderByDescending(Function(x) x.CreationTime) Try the following:
public class CompareFileInfoEntries : IComparer<FileInfo> { public int Compare(FileInfo f1, FileInfo f2) { return (string.Compare(f1.CreationTime.ToString(), f2.CreationTime.ToString())); } }