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;
} 暂时就只能做到这样,不知道会不会有更好的方法。