簡體   English   中英

如何在ASP.NET C#中沒有for / foreach循環的情況下綁定Treeview?

[英]How to bind Treeview without for/foreach loop in asp.net c#?

我試圖在沒有for / foreach循環的情況下綁定Treeview,這可能嗎? 如果是,那怎么辦?

表格結構-

Column1 | column2
------------------
root1   | val1
root1   | val2
root2   | val1
root2   | val2

我想要沒有for / foreach循環的樹形結構-

root1 
   val1
   val2
root2
   val1
   val2

我有編寫代碼來使用for / foreach循環執行此樹形視圖,如下所示,但我不想那樣做。

foreach (Product product in category.ProductList)
{
   TreeNode childNode = new TreeNode(product.ProductName, product.ProductID.ToString());
    parentNode.ChildNodes.Add(childNode);
}

也許您可以像下面的示例一樣使用Linq:

class Program
{
    class table
    {
        public string c1 { get; set; }
        public string c2 { get; set; }
    }
    class node
    {
        public string root { get; set; }
        public List<string> leafs { get; set; }
    }
    static void Main(string[] args)
    {
        List<table> list = new List<table>()
        {
            new table(){ c1="root1", c2="val1"},
            new table(){ c1="root1", c2="val2"},
            new table(){ c1="root1", c2="val3"},
            new table(){ c1="root2", c2="val1"},
            new table(){ c1="root2", c2="val2"},
        };

        var tree = (from l in list
                   group l by l.c1 into t
                   select new node { 
                       root = t.Key, 
                       leafs = t.Select(e => e.c2).ToList() 
                   }).ToList();

        foreach(node n in tree)
        {
            Console.WriteLine(n.root);
            foreach(string l in n.leafs)
            {
                Console.WriteLine("\t{0}", l);
            }
        }
        Console.ReadLine();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM