做一个用Treeview读取数据库信息的小程序,数据库中的信息诸如:


------解决思路----------------------
你要用一些小技巧,去提高判断是否存在的效率,比如把每个父节点,作为key添加到map中,每次创建父节点时,先到map中找一下,map是哈希,根据key判断非常快,如果有,就略过,没有在添加到treeview
------解决思路----------------------

public partial class Form1 : Form
{
List<Source> list = new List<Source>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
list.AddRange(new Source[] {
new Source("cq", "cq", "cq") { },
new Source("cq", "bj", "cq") { },
new Source("cq", "ba", "cq") { },
new Source("cc", "aa", "cc") { },
new Source("cc", "ac", "cc") { },
new Source("cc", "ad", "cc") { },
new Source("dd", "da", "dd") { },
new Source("dd", "db", "dd") { },
new Source("dd", "dc", "dd") { },
new Source("dd", "dd", "dd") { },
});
//选取父节点
var roots = list.Distinct(new BNameComparer()).Select(s => s.BName).ToList();
//遍历父节点
foreach (var item in roots)
{
TreeNode t = new TreeNode(item);
//父节点为当前节点的所有节点
var childern = list.Where(s => s.ParentNode == item).ToList();
foreach (var child in childern)
{
t.Nodes.Add(child.BDescription + "," + child.FName + "," + child.FNum.ToString() + "," + child.FDescription + "," + child.Map + "," + child.PixelDist);
}
treeView1.Nodes.Add(t);
}
}
}
public class BNameComparer : IEqualityComparer<Source>
{
public bool Equals(Source x, Source y)
{
if (x == null)
return y == null;
return x.BName == y.BName;
}
public int GetHashCode(Source obj)
{
if (obj == null)
return 0;
return obj.BName.GetHashCode();
}
}
public class Source
{
public Source(string bname, string fname, string pnode)
{
this.BName = bname;
this.BDescription = "cq";
this.FName = fname;
this.FNum = 1;
this.FDescription = "cq";
this.Map = "d:\\2.jpg";
this.PixelDist = "12";
this.ParentNode = pnode;
}
public string BName { get; set; }
public string BDescription { get; set; }
public string FName { get; set; }
public int FNum { get; set; }
public string FDescription { get; set; }
public string Map { get; set; }
public string PixelDist { get; set; }
//当前节点的父节点
public string ParentNode { get; set; }
}