C#用Linq填充treeview

时间:2014-07-02 18:34:51

标签: c# asp.net linq treeview

即时使用此代码填充我的树视图

var query = data.GroupBy(item => item.Column1)
                .Select(group => group.GroupBy(item => item.Column2))
                .Select(group => group.Select(innerGroup => 
                    innerGroup.GroupBy(item => item.Column3)));

和这些foreach代码

foreach (var outermostGroup in query)
{
    //add node for outermostGroup's key
    foreach (var middleGroup in outermostGroup)
    {
        //add child node of the above node for middleGroup key
        foreach (var innerGroup in middleGroup)
        {
            //add child node of the above node for innerGroup key
        }
    }
}

但是我得到并且错误尝试从outermostgroup和middleGroup Key获取密钥,但不是来自innerGroup,我不知道发生了什么。 例如。

foreach (var outermostGroup in query)
    {
      var node= new System.Web.Ui.WebControls.TreeNode(outermostGroup.Key)//here doesnt reconize me the key
        foreach (var middleGroup in outermostGroup)
        {
           var node= new System.Web.Ui.WebControls.TreeNode(middleGroup.Key)//here doesnt reconize me the key
            foreach (var innerGroup in middleGroup)
            {
                var node= new System.Web.Ui.WebControls.TreeNode(innerGroup.Key)//here recononize me the Key
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

你需要写这样的东西:

foreach (var outermostGroup in data.GroupBy(item => item.Column1))
{
    var node1 = new System.Web.Ui.WebControls.TreeNode(outermostGroup.Key);
    foreach (var middleGroup in outermostGroup.GroupBy(group => group.Column2))
    {
          var node2 = new System.Web.Ui.WebControls.TreeNode(middleGroup.Key);
          foreach (var innerGroup in middleGroup.GroupBy(group => group.Column3))
          {
              var node3 = new System.Web.Ui.WebControls.TreeNode(innerGroup.Key);
          }
    }
}