按編號分類的樹

來源:互聯網
上載者:User
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;
            }

暫時就只能做到這樣,不知道會不會有更好的方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.