我的输入

Sore | aye
A    |   1
A    |   2
A    |   3
B    |   1
B    |   2


outPut:我想将顶层表格排序到下面的treeview中

A
   1
   2
   3
B
   1
   2

最佳答案

给定此对象:

public class MyObject
{
    public string Sore { get; set; }
    public int aye { get; set; }
}


使用此数据:

var ls=new List<MyObject>();
ls.Add(new UserQuery.MyObject(){Sore="A",aye=1});
ls.Add(new UserQuery.MyObject(){Sore="A",aye=2});
ls.Add(new UserQuery.MyObject(){Sore="A",aye=3});
ls.Add(new UserQuery.MyObject(){Sore="B",aye=1});
ls.Add(new UserQuery.MyObject(){Sore="B",aye=2});


您可以很容易地做到这一点:

var result=ls.GroupBy (l =>l.Sore)
      .Select (l =>new
                    {
                        Root= l.Key,
                        Children=l.Select (x =>x.aye)
                    }
                ).ToList();


然后循环列表:

foreach (var root in result)
    {
        //root.Root to the root node
        foreach(var child in root.Children)
        {
            //Add the child to the root nodes children
        }
    }

09-05 13:53