如何在asp.net c#中绑定没有for/foreach循环的Treeview
本文关键字:for foreach 循环 Treeview 绑定 asp net | 更新日期: 2023-09-27 18:01:09
我正在尝试在没有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();
}
}