我有一个列表,里面有一些版本。
示例数据:
"4.5","2.1","2.2.1","7.5","7.5.3","N/A","2.3.4.5"
正如您所看到的数据,我正在尝试按降序排序列表 3.8.5
is invalid
number & 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/