0

I'm trying to sort the data in lambda expression in the following case.

if (Directory.Exists(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ErrorLogPath"].ToString())))
{
    string path = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ErrorLogPath"].ToString());
    // a.Select(p => Path.GetFileNameWithoutExtension(p));
    var a = Directory.GetFiles(path);
    if (a != null)
    {
        Session["gvData"] = a.ToList();
        BindDataToGrid();
    }
}

In var a i get list of complete path of files like

c:\\logfiles\\01022012.txt. 

How can I get var a sorted on basis of 01022012 I tried

var a = Directory.GetFiles(path).OrderBy(p=>Path.GetFileNameWithoutExtension(p));

but not working. Is there any thing am I doing wrong?

Getting result as

"C:\\LogFiles\\01112012.txt" 
"C:\\LogFiles\\08102012.txt" 
"C:\\LogFiles\\14092012.txt" 
"C:\\LogFiles\\15102012.txt" 
"C:\\LogFiles\\17102012.txt" 
"C:\\LogFiles\\19092012.txt" 

Expected is

"C:\\LogFiles\\14092012.txt" 
"C:\\LogFiles\\19092012.txt" 
"C:\\LogFiles\\08102012.txt" 
"C:\\LogFiles\\15102012.txt" 
"C:\\LogFiles\\17102012.txt" 
"C:\\LogFiles\\01112012.txt" 
4

1 回答 1

2
var a = Directory.GetFiles(path)
                 .OrderBy(p => Regex.Replace(p,@"^.*\\(\d\d)(\d\d)(\d\d\d\d).*$","$3$2$1"))

The order worked but was an alphabetical order, whereas you want a chronological order. The trick is to turn ddMMyyyy into yyyyMMdd (thanks to the regex) and then then alphabetical and chronological orders become identical.

于 2012-11-03T10:10:03.593 回答