[英]How to clean up “TreeNode”s with same Text property in a TreeView?
我有一个TreeView,其中将填充一些Node。 问题在于,此节点可以具有不同的Tag
和Name
属性,但是其中一些节点可以具有相同的Text
属性。
我只希望上述每个节点中只有一个节点,因此TreeView将通过Text
具有唯一的节点。
我试图制作所有节点的列表,然后过滤它们,然后将新列表添加到TreeView。 这是我的方法,我评论了未编译的行。
//Remove Duplicated Nodes
List<TreeNode> oldPinGrpNodes = new List<TreeNode>();
List<TreeNode> newPinGrpNodes = new List<TreeNode>();
TreeNode tempNode;
foreach (TreeNode node in tvPinGroups.Nodes)
{
oldPinGrpNodes.Add(node);
}
foreach (TreeNode node in oldPinGrpNodes)
{
if (newPinGrpNodes.Contains(node.Text)) continue; //this does not compile!
//How to do a check in the IF statement above?
//Continue with adding the unique pins to the newList
}
或者,如果您有更好的主意,请告诉我!
您是否尝试过以下Linq查询而不是检查?
if (newPinGrpNodes.Any(n => n.Text == node.Text)) continue;
尝试这个。 我在System.Linq
使用ToLookup
扩展方法:
//Remove Duplicated Nodes
List<TreeNode> oldPinGrpNodes = new List<TreeNode>();
Dictionary<string, TreeNode> newPinGrpNodes = new Dictionary<string, TreeNode>();
TreeNode tempNode;
foreach (TreeNode node in tvPinGroups.Nodes)
{
oldPinGrpNodes.Add(node);
}
foreach (TreeNode node in oldPinGrpNodes)
{
if (newPinGrpNodes.ContainsKey(node.Text)) continue; //this does not compile!
//How to do a check in the IF statement above?
//Continue with adding the unique pins to the newList
// do something like
newPinGrpNodes.Add(node.Text, node);
}
至于您的编译错误, newPinGrpNodes
- TreeNode
类型的集合,您尝试在该位置搜索string
。
更新:为了提高性能,最好使用Dictionary搜索项目: Dictionary<string, TreeNode>
而不是List<TreeNode>
。
if(newPinGrpNodes.Any(n => n.Text==node.Text)) continue;
foreach (TreeNode node in oldPinGrpNodes)
{
if ( from m in newPinGrpNodesLookup where m.text=node.Text select m).first ==null)
continue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.