c# - 如何在 C# 中按降序版本列表排序?

标签 c# .net linq

我有一个列表,里面有一些版本。

示例数据:

"4.5","2.1","2.2.1","7.5","7.5.3","N/A","2.3.4.5"

正如您所看到的数据,我正在尝试按降序排序列表 3.8.5 is invalidnumber & NA is一个无效的。

代码:

decimal result;
var sortedVData = vData.OrderByDescending(v => decimal.TryParse(v.vCode, out result) ? Convert.ToDecimal(v.vCode) : decimal.MaxValue);

输出: “NA”、“7.5.3”、“2.3.4.5”、“2.2.1”、“7.5”、“4.5”、“2.1”

正如您在我的 else(:) 条件中看到的那样,我正在执行 decimal.MaxValue 以使 NA 在有无效值(任何带文本的字符串)但 2.2.1 应该是一个异常(exception)并且应该作为数字工作(艰难的 2.2.1 或任何具有多个小数的数字在版本的观点中是无效的我想要它们有条件地有效。

预期结果: “NA”、“7.5.3”、“7.5”、“4.5”、“2.3.4.5”、“2.2.1”、“2.1”

最佳答案

您可以使用 Version.TryParse以及 LINQ 查询的扩展方法:

public static Version TryGetVersion(this string item)
{
    Version ver;
    bool success = Version.TryParse(item, out ver);
    if (success) return ver;
    return null;
}

那么完整的查询就很简单了:

var sortedVData = vData
    .Select(v => new { Obj = v, Version = v.vCode.TryGetVersion() })
    .OrderBy(x => x.Version != null)    // first all invalid versions
    .ThenByDescending(x => x.Version)   // then by version descending
    .Select(x => x.Obj);

所以实际上存储versions会更好而不是您类(class)中的字符串。

better to use this extension in LINQ queries而不是使用局部变量。

关于c# - 如何在 C# 中按降序版本列表排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34609395/

相关文章:

c# - 用于搜索嵌套级别的正则表达式

c# - Azure AD SSO : .Net Core 2.1 基于组织的 Office 365 用户名和密码的单点登录

c# - 检索 Entity Framework Core 生成的 SQL

c# - 使用 Linq 解析 XML 时,只会获取一个对象

c# - 办公室 365 API : Add a contact to an organisation distribution list

.net - Shersoft 和 ActiveListBar 控件发生了什么?

c# - 继承相等比较器

c# - .Net CultureInfo Month Names 返回一个额外的空字符串

c# - 有没有更好或更有效的方法来使用 linq 进行过滤

c# - 带条件搜索的 Lambda 表达式,仅返回 1 个最新结果