简体   繁体   English

按字符串排序列表以查找较新的版本C#

[英]Ordering a List by string to find the newer version C#

I have a folder with several Directories that are named after a version of an update such as UPDATE_20080311_3.5.9. 我有一个包含多个目录的文件夹,这些目录以更新版本(例如UPDATE_20080311_3.5.9)命名。 I need to find the latest update on that list by veryfing the "3.5.9", I made a code to parse the name and add just the version to a list. 我需要通过紧扣“ 3.5.9”来找到该列表的最新更新,我编写了代码以解析名称并将其仅添加到列表中。 Is there anyway to Sort tha list by using List.Sort in order to get the latest version "number"? 无论如何,有没有使用List.Sort对列表进行排序以获取最新版本的“数字”? This is the code I made so far, I don't know how to properly use the .Sort() method and if this can be done. 这是我到目前为止编写的代码,我不知道如何正确使用.Sort()方法,以及是否可以这样做。 I appreciate any help given 我感谢您提供的任何帮助

public string NewerVersion(string Directoria)
    {
        List<string> Lista = new List<string>();
        DirectoryInfo dir = new DirectoryInfo(Directoria);
        DirectoryInfo[] dirs = dir.GetDirectories();
        foreach (DirectoryInfo Info in dirs)
        {
            string Dir = Info.Name.ToString();
            Lista.Add(Dir.Substring(Dir.LastIndexOf('_'), Dir.Length));

        }
        Lista.Sort()
        //Lista.ToArray();
    }

You can use Version which implements IComparable , so it supports sorting. 您可以使用实现IComparable Version ,因此它支持排序。

For example with this LINQ query: 例如,使用此LINQ查询:

Version version = null;
Version lastVersion = new DirectoryInfo(Directoria).EnumerateDirectories()
    .Where(d => d.Name.StartsWith("UPDATE_"))
    .Select(d => new {Directory = d, Token = d.Name.Split('_')})
    .Where(x => x.Token.Length == 3 && Version.TryParse(x.Token[2], out version))
    .Select(x => new {x.Directory, Date = x.Token[1], Version = version})
    .OrderByDescending(x => x.Version)
    .Select(x => x.Version)
    .FirstOrDefault();
string latestVersion = lastVersion.ToString(); // if you want it as string

After I find the newer version I need to be able to return the name of the directory 找到较新的版本后,我需要能够返回目录的名称

Then use this query: 然后使用以下查询:

var lastVersion = new DirectoryInfo(Directoria).EnumerateDirectories()
    .Where(d => d.Name.StartsWith("UPDATE_"))
    .Select(d => new {Directory = d, Token = d.Name.Split('_')})
    .Where(x => x.Token.Length == 3 && Version.TryParse(x.Token[2], out version))
    .Select(x => new {x.Directory, Date = x.Token[1], Version = version})
    .OrderByDescending(x => x.Version)
    .FirstOrDefault();
if (lastVersion != null)
    Console.WriteLine(lastVersion.Directory.FullName);

When sorting by version , try using Version which is specially designed for that: 版本排序时,请尝试使用专门为此设计的Version

 List<String> Lista = new List<string>() {
    "UPDATE_20080311_3.5.9",
    "UPDATE_20080311_3.5.10",
    "UPDATE_20080311_3.4.11",
  };

  Lista.Sort((left, right) => {
    Version x = new Version(left.Substring(left.LastIndexOf('_') + 1));
    Version y = new Version(right.Substring(right.LastIndexOf('_') + 1));

    // or "return -x.CompareTo(y);" if you want to sort in descending order
    return x.CompareTo(y);
  });

  ...

  // UPDATE_20080311_3.4.11
  // UPDATE_20080311_3.5.9
  // UPDATE_20080311_3.5.10
  Console.Write(String.Join(Environment.NewLine, Lista);

Edit: 编辑:

Continuing from your solution, there is a problem which the way you add your item: 从您的解决方案继续,存在添加项目方式的问题:

string Dir = Info.Name.ToString();
Lista.Add(Dir.Substring(Dir.LastIndexOf('_'), Dir.Length));

Notice two mistakes here: 请注意此处的两个错误:

  1. You get the Substring from LastIndexOf('_') instead of from LastIndexOf('_') + 1 , which is what you really want 您从LastIndexOf('_')而不是从LastIndexOf('_') + 1获得Substring ,这是您真正想要的
  2. You use Dir.Length while you should use Dir.Length - LastIndexOf('_') + 1 instead 您应使用Dir.Length而应使用Dir.Length - LastIndexOf('_') + 1代替

Change that into: 将其更改为:

string Dir = Info.Name.ToString();
int indexStart = Dir.LastIndexOf('_') + 1;
Lista.Add(Dir.Substring(indexStart, Dir.Length - indexStart));

Then you could further process the Lista that you have populated to have the version number alone by LINQ OrderBy and ThenBy as well as string.Split('.') 然后,您可以进一步处理已填充的Lista ,以使其仅具有LINQ OrderByThenBy的版本号以及string.Split('.')

var result = Lista.Select(x => x.Split('.'))
    .OrderBy(a => Convert.ToInt32(a[0]))
    .ThenBy(a => Convert.ToInt32(a[1]))
    .ThenBy(a => Convert.ToInt32(a[2]))
    .Last();
string finalVersion = string.Join(".", result);

To get the final version among the listed items. 在所列项目中获取最终版本。

To get your directory path back based on your finalVersion , simply do: 要基于finalVersion返回目录路径,只需执行以下操作:

string myDirPath = dirs.Select(x => x.FullName).SingleOrDefault(f => f.EndsWith(finalVersion));

You can use Linq and Version 您可以使用LinqVersion

public string NewerVersion(string Directoria)
{
    return new DirectoryInfo(Directoria)
        .GetDirectories()
        .OrderByDescending(x => new Version(x.Name.Substring(x.Name.LastIndexOf('_') + 1)))
        .First()
        .Name;
}

If Directoria contains "UPDATE_20080311_3.5.9", "UPDATE_20090311_5.6.11", "UPDATE_20070311_1.5.9" , will return "UPDATE_20090311_5.6.11" 如果Directoria包含"UPDATE_20080311_3.5.9", "UPDATE_20090311_5.6.11", "UPDATE_20070311_1.5.9" ,则将返回"UPDATE_20090311_5.6.11"

I'm not sure about, whether this satisfies the requirement or not;if not please forgive me; 我不确定这是否满足要求;否则请原谅。

You are creating folders for each version release; 您正在为每个版本发行创建文件夹; so a version 3.5.7 will be created after 3.5.6 which is followed by 3.55 and the next version could be 3.58 , So what i'am trying to say is that, they can be sorted on the basics of creation time. 因此,将在3.5.6之后创建一个3.5.7版本,然后是3.55 ,下一个版本可能是3.58 ,所以我想说的是,可以根据创建时间的基础对它们进行排序。 if so the following code will help you: 如果是这样,以下代码将为您提供帮助:

public static string NewerVersion(string Directoria)
{
    List<string> Lista = new List<string>();
    DirectoryInfo dir = new DirectoryInfo(Directoria);
    DirectoryInfo[] dirs = dir.GetDirectories();
    Lista = dirs.OrderBy(x => x.CreationTime).Select(y => y.Name.ToString()).ToList();
    //Lista will contains the required names
    //rest of code here
    return String.Join(Environment.NewLine, Lista);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM