You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 10 WinForms TreeView如何用CompareOptions.NumericOrdering实现数字排序

实现WinForms TreeView的数字自然排序(.NET 10)

核心思路

利用.NET 10新增的CompareOptions.NumericOrdering,结合StringComparer自定义TreeView的排序规则,无需手动解析字符串中的数字,就能实现Windows资源管理器风格的数字排序。

具体实现步骤

  1. 设置TreeView的自定义排序器
    在窗体初始化时(比如构造函数、Form_Load事件中),为TreeView指定带数字排序的字符串比较器:
using System.Globalization;
using System.Windows.Forms;

public YourForm()
{
    InitializeComponent();
    // 绑定支持数字排序的比较器
    treeView1.TreeNodeSorter = StringComparer.Create(CultureInfo.CurrentCulture, CompareOptions.NumericOrdering);
}
  1. 触发排序
    和你之前的操作一致,通过上下文菜单调用treeView1.Sort()即可完成排序:
private void SortToolStripMenuItem_Click(object sender, EventArgs e)
{
    treeView1.Sort();
}

可选配置

  • 如果需要忽略大小写排序,可在CompareOptions中添加IgnoreCase:
treeView1.TreeNodeSorter = StringComparer.Create(CultureInfo.CurrentCulture, CompareOptions.NumericOrdering | CompareOptions.IgnoreCase);
  • 若要使用特定文化区域的排序规则,替换CultureInfo.CurrentCulture为目标文化(比如CultureInfo.InvariantCulture)即可。

效果说明

设置完成后,TreeView的节点会按照「字符串+数字」的自然顺序排序,例如:Document1、Document2、Document10、Document11,完全符合需求。

内容的提问来源于stack exchange,提问作者Terry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 23:24:51