如何在asp.net c#中使用/ foreach循环绑定Treeview?

时间:2015-07-06 13:13:39

标签: c# asp.net treeview

我试图在没有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);
}

1 个答案:

答案 0 :(得分:0)

也许你可以像下面的例子一样使用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();
    }
}