【问题标题】:How to use the Version Class in a LINQ query on latest release folder如何在最新版本文件夹的 LINQ 查询中使用版本类
【发布时间】:2014-01-28 13:31:02
【问题描述】:

我们正在进行软件构建并将它们存储在预发布文件夹中的文件夹中,格式为四位数 Major.Minor.Build.rev (0.0.0.0)。

  1. 我想知道是否有办法在 LINQ 查询中使用版本类?
  2. 使用 LINQ 查询会有什么好处,还是应该坚持使用非 LINQ 查询代码?

这是我目前拥有的代码:

static void Main(string[] args)
{
    string latest = GetLatestBuildVersion(@"\\path\to\network\folder");
    latest = "";
}

static string GetLatestBuildVersion(string sPath)
{
    Version latestVersion = new Version();
    string[] dirs = Directory.GetDirectories(sPath);
    foreach (string dir in dirs)
    {
        string subfolderNameOnly = Path.GetFileName(dir);
        try
        {
            Version subfolderVersion = new Version(subfolderNameOnly);
            if (latestVersion.CompareTo(subfolderVersion) < 0)
            {
                latestVersion = subfolderVersion;
            }
        }
        catch (Exception ex)
        {
            // Just continue
        }
    }
    return latestVersion.ToString();
}

【问题讨论】:

  • 如果您已经有了可以工作的代码,那么您似乎应该坚持下去。任何获得的优势都非常小。
  • 它确实有效。我希望用更少的代码来做到这一点。我有一些代码可以查询到某个点,但是我卡在 Path.GetFileName 和 subfolderversion 的版本类的第二个实例上。

标签: c# linq linq-to-objects


【解决方案1】:

这是链式 LINQ 方法的完美任务:

static string GetLatestBuildVersion(string sPath)
{
    return Directory.GetDirectories(sPath)
        .Select(v => new Version(Path.GetFileName(v)))
        .OrderBy(v => v)
        .Last();
}

根据需要添加错误处理(考虑到特定的上下文,我宁愿让它爆炸,而不是让它在不是我期望它们的位置/位置的文件上运行)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2022-06-17
    • 2019-08-09
    相关资源
    最近更新 更多