我有一個樹狀結構列表數不同的樹如下:如何在樹木
public class TAGNode
{
public string Val;
public string Type = "";
private List<TAGNode> childs;
public IList<TAGNode> Childs
{
get { return childs.AsReadOnly(); }
}
public TAGNode AddChild(string val)
{
TAGNode tree = new TAGNode(val);
tree.Parent = this;
childs.Add(tree);
return tree;
}
public override bool Equals(object obj)
{
var t = obj as TAGNode;
bool eq = Val == t.Val && childs.Count == t.Childs.Count;
if (eq)
{
for (int i = 0; i < childs.Count; i++)
{
eq &= childs[i].Equals(t.childs[i]);
}
}
return eq;
}
}
我有這樣的樹可以包含重複樹的列表,通過重複我的意思它們具有相同標籤的相同結構。現在我想從這個列表中選擇不同的樹。我試過
etrees = new List<TAGNode>();
TAGNode test1 = new TAGNode("S");
test1.AddChild("A").AddChild("B");
test1.AddChild("C");
TAGNode test2 = new TAGNode("S");
test2.AddChild("A").AddChild("B");
test2.AddChild("C");
TAGNode test3 = new TAGNode("S");
test3.AddChild("A");
test3.AddChild("B");
etrees.Add(test1);
etrees.Add(test2);
etrees.Add(test3);
var results = etrees.Distinct();
label1.Text = results.Count() + " unique trees";
這會返回所有樹的數量(3),而我期望2棵不同的樹!我想也許我應該爲它實施一個合適的Equals
函數,但是正如我測試的那樣,它並不關心Equals
返回什麼!
謝謝,可能是TagNode的GetHashCode!? – Ahmad
http://stackoverflow.com/questions/1988665/hashing-a-tree-structure – Nahum
我修改了我的問題,以顯示我的Equals實現,不知道如何映射到GetHashCode,是不是一個更好的方法!我需要提供GetHashCode?!! – Ahmad