gpt4 book ai didi

C# - 仅按父节点对 TreeView 进行排序

转载 作者:行者123 更新时间:2023-11-30 16:01:04 25 4
gpt4 key购买 nike

我有一个排序如下的TreeView(treeViewNew)

  • parent 姓名1

    • 第一场
    • 字段 2
    • 字段 3
    • 等等...
  • parent 姓名2

    • 等等...

有大约 300 个父条目。我希望能够通过按字母/数字顺序对父节点进行排序来重新排序我的所有节点,同时携带它们的子节点而不对它们进行排序,因为子节点相对于 parent ,不能改变。我很难想出一个 TreeViewNodeSorter 可以正确地完成它。有什么想法吗?

最佳答案

因为传递给 IComparer 的对象是 TreeNode 对象,您可以通过检查 Parent< 来确定给定节点是子节点还是根节点 属性。如果它们不是根节点,那么您唯一需要做的就是返回一个值,以确保它们保持相同的顺序。

此比较器按名称比较根节点,按索引比较非根节点。这保留了非根节点的顺序。

public class Sorter : IComparer
{
public int Compare(object x, object y)
{
var tx = x as TreeNode;
var ty = y as TreeNode;

// If this is a child node, preserve the same order by comparing the node Index, not the text
if (tx.Parent != null && ty.Parent != null)
return tx.Index - ty.Index;

// This is a root node, compare by name.
return string.Compare(tx.Text, ty.Text);
}
}

关于C# - 仅按父节点对 TreeView 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39130744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com