Sorting a List<FileInfo> by creation date C#

断了今生、忘了曾经 提交于 2019-12-04 03:08:26

问题


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() )));

回答1:


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



回答2:


Umm what about using linq

files.OrderBy(f=>f.CreationTime)



回答3:


Dim filePath as string = "c:\\"

This command get directory file list ordered by ASC

Dim orderedFiles = New System.IO.DirectoryInfo(filePath).GetFiles("*.xml")
                                                        .OrderBy(Function(x) x.CreationTime)

This command get directory file list ordered by DESC

Dim orderedFiles = New System.IO.DirectoryInfo(filePath).GetFiles("*.xml")
                                                        .OrderByDescending(Function(x) x.CreationTime)



回答4:


Try this:

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


来源:https://stackoverflow.com/questions/9001544/sorting-a-listfileinfo-by-creation-date-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!