1昨天做一個產品分類,以前分類都是id和fid的方式來進行的,但這種做法在產品查詢的時候需要嵌套,切效率不高。於是定義一個簡單的分類。
首先是定義格式
TypeId TypeName;
分類從01開始,每2位為一級。
01 一級
0101 二級
010101 三級
每個分類支援99個,如果需要擴充,則可用16進位表示擴充到255個。
以下是資料庫中的內容Code
TypeId TypeName
01 1
0101 11
010101 111
010102 112
0102 12
010201 121
01020101 444444
01020102 44444
010202 122
0103 13
010301 132
0104 21
0105 22
0106 23
02 3
0201 31
0202 32
020201 44
020202 444
03 4
0301 41
0302 42
0303 44
0304 444
0305 4
030501 44444
03050101 444444
04 5
根據以上的規律,構建了一個樹的結構,並規定,如果TypeId為“00“作為根節點。Code
public class TreeNode {
public TreeNode Parent;
public string Id { set; get; }
public string Name { set; get; }
public IList<TreeNode> Nodes { get; set; }
public TreeNode() {
Nodes = new List<TreeNode>();
}
public void Append(TreeNode node) {
if (this.Id == "00")
{
node.Parent = this;
this.Nodes.Add(node);
}
else
{
if (node.Id.Length == this.Id.Length + 2)
{
node.Parent = this;
this.Nodes.Add(node);
}
if (node.Id.Length <= this.Id.Length) {
this.Parent.Append(node);
}
}
}
}
這樣,一次讀出所有資料,就可以產生一棵樹了。Code
var goodstypeAll = (from c in ctx.TBL_GoodsTypes select c).OrderBy(c => c.TypeId);
TreeNode root = new TreeNode();
root.Parent = new TreeNode();
root.Id = "00";
root.Name = "根";
root.Nodes = new List<TreeNode>();
TreeNode tmp = root;
foreach (TBL_GoodsType key in goodstypeAll) {
TreeNode node = new TreeNode();
node.Id = key.TypeId;
node.Name = key.TypeName;
node.Nodes = new List<TreeNode>();
tmp.Append(node);
tmp = node;
}
暫時就只能做到這樣,不知道會不會有更好的方法。