以树影风格展示

时间:2012-04-21 11:01:34

标签: c#

我的输入

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

outPut:我想将顶层表排在树视图下面

A
   1 
   2 
   3
B  
   1
   2 

2 个答案:

答案 0 :(得分: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
        }
    }

答案 1 :(得分:1)

var str = "Sore | aye\r\nA    |   1 \r\nA    |   2\r\nA    |   3\r\nB    |   1\r\nB    |   2";

var relations = str.Split(new[] {Environment.NewLine},
                          StringSplitOptions.RemoveEmptyEntries)
                   .Skip(1).Select(l => l.Split('|').Select(
                                   x => x.Trim()).ToArray()).ToArray();

var relationsDic = new SortedDictionary<string, SortedSet<string>>();

foreach (var relation in relations)
{
    if (relationsDic.ContainsKey(relation[0]))
    {
        relationsDic[relation[0]].Add(relation[1]);
    }
    else
    {
        relationsDic[relation[0]] = new SortedSet<string> {relation[1]};
    }
}

foreach (var kvp in relationsDic)
{
    Console.WriteLine(kvp.Key);

    foreach (var sub in kvp.Value)
    {
        Console.WriteLine("\t" + sub);
    }
}