c# - Sorting a file by the content of it's filename -


i have list of files sort based on date. caveat each file in list contains date part of it's file name, want sort files based on date. reason because date in file name string correlates content in file, i.e. actual date property of each file, date created, modified, accessed, etc, subject change whenever file moved or modified , cannot rely on purposes. i'm creating custom comparer use in list sorting method, wanted see if out there has other better or unique approaches this. in advance.

update:

in answer saeed's comment, file name follows format:

{test name}_{yyyymmdd}_{hhmmss}.txt 

where yyyymmdd , hhmmss date , time, respectively.

update 2:

ok, got comparer written seems job fine, here if helps else; wouldn't take effort alter search other elements in file name, need change regular expression. suggestions, constructive criticism welcome.

public class tdrdatetimecomparer : icomparer<fileinfo> {     public int compare(fileinfo x, fileinfo y)     {        //return if both strings null or empty         if (string.isnullorempty(x.name) && string.isnullorempty(y.name))         {             return 0;         }         regex rdatetime = new regex(@"(19|20|21)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])_([0-1]\d|2[0-3])([0-5]\d)([0-5]\d)");          /* note: file names have been validated @ point, no need validate date/time again.*/         string date1 = rdatetime.match(x.name).value, date2 = rdatetime.match(y.name).value;         datetime d1 = datetime.parseexact(date1, "yyyymmdd_hhmmss", null), d2 = datetime.parseexact(date2, "yyyymmdd_hhmmss", null);          return d1.compareto(d2);     } } 

i'd custom comparer way go. use regex extract date parts, create datetime out of , compare those.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -