Mat*_*ich 4 c# sorting treeview
我有一个 TreeView (treeViewNew) 排序如下
父母姓名1
父母姓名2
大约有 300 个父条目。我希望能够通过仅按字母顺序/数字顺序对父节点进行排序来重新排序我的所有节点,携带其子节点而不对其进行排序,因为子节点相对于父节点按特定顺序排列并且无法更改。我很难想出一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)