1

I have little to no knowledge with C#. That being said, I have been tasked with a project of sorting a list based on the latest version of jQuery in a folder where a bunch of versions are held.

Currently, this is what I have:

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

I have been thinking about ways I can go about doing this for a few days now, and have come up with little to no results(at least ones that work).

Any suggestions or help will be greatly appreciated.

Matt Bettiol
  • 309
  • 1
  • 3
  • 9
  • 7
    Well yes, you're sorting the list... so what's the question? (I'd personally use LINQ to do all of this, but that's a different matter. What you've got should work, assuming `mydir.GetFiles()` works.) – Jon Skeet May 20 '14 at 15:06
  • 3
    Have you tried googling "sorting a list with C#"? – catfood May 20 '14 at 15:06
  • 1
    possible duplicate of [C# List<> OrderBy Alphabetical Order](http://stackoverflow.com/questions/188141/c-sharp-list-orderby-alphabetical-order) – catfood May 20 '14 at 15:07
  • I'm guessing the version of JQuery is displayed in the names of the files, if that is the case you need to give us some examples of the file names, then I maybe able to put something together for you – Ben May 20 '14 at 15:08
  • How do you want to detect the version of jQuery, do you have a plan or is this your actual question? If you know how to get it, tell it us. – Tim Schmelter May 20 '14 at 15:21
  • If you are going to be working in C# I would recommend learning LINQ... it will **definitely** help you in the long run. – Kevin May 20 '14 at 15:49

4 Answers4

1

Assuming an alphabetical ordering will put it in the right order... your code to get the ordered list could look like this....

I'm using LINQ method syntax and comment each line since you mentioned you don't know a lot about 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]);
    }
Kevin
  • 4,586
  • 23
  • 35
  • Currently, this is what I see: jquery-1.10.2.min.js jquery-1.11.0.min.js jquery-1.5.1.min.js I need so jquery-1.11.0.min.js would be teh first result that is show in the list – Matt Bettiol May 20 '14 at 15:13
  • 2
    @StevenSmith what do your filenames look like and I can add code that strips the version numbers out of the strings to sort them by. – Kevin May 20 '14 at 15:17
  • @StevenSmith Alphabetically, `10` comes before `11` comes before `5`. – Kris Vandermotten May 20 '14 at 15:18
  • This is what my list currently looks like: http://gyazo.com/64e8d951b97a485c00e4d62cee0c8a20 I'm trying to make it sort by the latest version of jQuery – Matt Bettiol May 20 '14 at 15:20
  • @StevenSmith take a look at my latest edits... they should work for you. – Kevin May 20 '14 at 15:43
0

not intended to be a complete solution but this should get you close.

    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; }
    }
workabyte
  • 3,496
  • 2
  • 27
  • 35
  • There's already a [`Version`](http://msdn.microsoft.com/en-us/library/system.version.aspx)-class which you can use, it has also a builtin sorting by major, minor, built. – Tim Schmelter May 20 '14 at 15:25
  • @TimSchmelter yes this is true but i checked the file attributes for the jQuery file, did not look like that was set. – workabyte May 20 '14 at 15:26
  • 1
    What i meant to say was that you can use a `Version` in your class instead of strings. Then you could also use that for `OrderByDescending` directly without needing to use all the `...ThenBy`. You can initialize it either the same way you're setting your properties or by using `Version` parse. – Tim Schmelter May 20 '14 at 15:37
  • @TimSchmelter, true. just threw this together fast. ill change it later. good constructive criticism, thank you :) – workabyte May 20 '14 at 15:41
0

I have created a class to do all the work for me, but you don't have to do that, I just find it easier. I use a regex to pull the version number out of the file name, then split that into the 3 integer parts of the version number.

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;
    }
}

You can then create and sort the list of JQueryVersion objects like this:

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]);
Ben
  • 5,525
  • 8
  • 42
  • 66
0

I personnaly use Sort(Comparison< T >) for homemade comparisons :
http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=vs.110%29.aspx

Here is an example comparing your files modification dates :

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);
}
Hybris95
  • 2,286
  • 2
  • 16
  • 33