用c# *非字母顺序*排序列表

本文关键字:顺序 排序 列表 | 更新日期: 2023-09-27 18:04:28

我对c#几乎一无所知。话虽这么说,我有一个项目的任务是根据最新版本的jQuery在一个文件夹中排序一个列表,这个文件夹中保存了很多版本。

目前,这是我的:

public ActionResult Index()
{
    //creating a DirectoryInfo object
    DirectoryInfo mydir = new DirectoryInfo(@"''edcapptest'E$'cdn'js'jquery");
    // getting the files in the directory
    FileInfo[] f = mydir.GetFiles();
    List<string> myList = new List<string>();
    foreach (FileInfo file in f)
    {
        myList.Add(file.Name);
    }
    myList.Sort();
    return View(myList);
}

几天来,我一直在思考如何做到这一点,但几乎没有任何结果(至少是有效的)。

如有任何建议或帮助,我将不胜感激。

用c# *非字母顺序*排序列表

假设按字母顺序排列会把它放在正确的位置…获取有序列表的代码如下所示....

我正在使用LINQ方法语法并注释每一行,因为你提到你对c#了解不多。

public ActionResult Index()
{
    //creating a DirectoryInfo object
    DirectoryInfo mydir = new DirectoryInfo(@"''edcapptest'E$'cdn'js'jquery");
    // getting the files in the directory
    var myList = mydir.GetFiles()  // Your objects in the list you start with
        // Filter for the jquery files... you may not need this line
        .Where(file => file.Name.StartsWith("jquery-"))
        // Select the filename and version number so we can sort  
        .Select(file => new { Name= file.Name, Version = GetVersion(file.Name)}) 
        // OrderBy the version number
        .OrderBy(f => f.Version)
        // We have to select just the filename since that's all you want
        .Select(f => f.Name)
        // Convert your output into a List 
        .ToList();                 
    return View(myList);
}
    // GetVersion code and regex to remove characters...
    private static Regex digitsOnly = new Regex(@"[^'d]");
    public static Version GetVersion(string filename)
    {
        var versionNumbers = new List<int>();
        var splits = filename.Split('.');
        foreach (var split in splits)
        {
            var digits = digitsOnly.Replace(filename, "");
            if (!string.IsNullOrEmpty(digits))
                versionNumbers.Add(int.Parse(digits));
        }
        // Create a version which can have various major / minor versions and 
        //   handles sorting for you.
        return new Version(versionNumbers[0], versionNumbers[1], 
                       versionNumbers[2]);
    }

不是一个完整的解决方案,但这应该让你接近。

    public List<jquery> GetVersion(string path)
    {
        var thelist = (from afile in System.IO.Directory.EnumerateFiles(path)
            let version = removeLetters(afile)
            select removeLetters(afile).Split('.')
            into splitup
            select new jquery()
            {
                Filename = filename,
                //will want to add some additional checking here as if the length is not 3 then there will be other errors.
                //just a starting point for you
                Major = string.IsNullOrWhiteSpace(splitup[0]) ? 0 : int.Parse(splitup[0]), 
                Minor = string.IsNullOrWhiteSpace(splitup[1]) ? 0 : int.Parse(splitup[1]), 
                Build = string.IsNullOrWhiteSpace(splitup[2]) ? 0 : int.Parse(splitup[2]),
            }).ToList();
        return thelist
            .OrderByDescending(f => f.Major)
            .ThenByDescending(f => f.Minor)
            .ThenByDescending(f => f.Build)
            .ToList();
    }
    public string removeLetters(string value)
    {
        var chars = value.ToCharArray().Where(c => Char.IsNumber(c) || c.Equals('.'));
        return chars.ToString();
    }
    public class jquery
    {
        public string Filename { get; set; }
        public int Major { get; set; }
        public int Minor { get; set; }
        public int Build { get; set; }
    }

我已经创建了一个类来为我做所有的工作,但你不必这样做,我只是觉得它更容易。我使用正则表达式从文件名中提取版本号,然后将其分成版本号的3个整数部分。

public class JQueryVersion
{
    public string File_Name { get; set; }
    public string Version
    {
        get
        {
            return Regex.Match(this.File_Name, @"jquery-([0-9]{1,2}'.[0-9]{1,2}'.[0-9]{1,2})'.").Groups[1].Value;
        }
    }       
    public int[] Version_Numeric
    {
        get
        {
            return this.Version.Split('.').Select(v => int.Parse(v)).ToArray();
        }
    }
    public JQueryVersion (string File_Name)
    {
        this.File_Name = File_Name;
    }
}

你可以这样创建和排序JQueryVersion对象列表:

List<JQueryVersion> Data = new List<JQueryVersion>()
{
    new JQueryVersion("jquery-1.10.2.min.js"),
    new JQueryVersion("jquery-1.11.0.min.js"),
    new JQueryVersion("jquery-1.5.1.min.js"),
    new JQueryVersion("jquery-1.6.1.min.js"),
    new JQueryVersion("jquery-1.6.2.min.js"),   
};
var Sorted_Data = Data
    .OrderByDescending (d => d.Version_Numeric[0])
    .ThenByDescending (d => d.Version_Numeric[1])
    .ThenByDescending (d => d.Version_Numeric[2]);

我个人使用Sort(比较)用于自制比较:
http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=vs.110%29.aspx

下面是一个比较文件修改日期的例子:

public ActionResult Index()
{
    //creating a DirectoryInfo object
    DirectoryInfo mydir = new DirectoryInfo(@"''edcapptest'E$'cdn'js'jquery");
    // getting the files in the directory
    FileInfo[] f = mydir.GetFiles();
    List<string> myList = new List<string>();
    foreach (FileInfo file in f)
    {
        myList.Add(file.Name);
    }
    myList.Sort(SortByModificationDate);
    return View(myList);
}
public int SortByModificationDate(string file1, string file2)
{
    DateTime time1 = File.GetLastWriteTime(file1);
    DateTime time2 = File.GetLastWriteTime(file2);
    return time1.CompareTo(time2);
}