列表通过linq对树视图进行排序

时间:2012-06-10 08:29:24

标签: c# linq sorting

我有一个清单

key ParentKey
1   Null
2   1
3   Null
4   Null
5   1
6   4
7   6
8   3

我希望它在

中排序
key ParentKey
1   Null
2   1
5   1
3   Null
8   3
4   Null
6   4
7   6

通过linq如何做到这一点? 任何帮助都是最好的结果

3 个答案:

答案 0 :(得分:1)

假设结果应为:

key ParentKey
1   Null
2   1
5   1
3   Null
8   3
4   Null
6   4
7   6

我可以说如果没有逻辑将该位置的空值放入列表中,则无法执行任何操作。

因此,使用Linq,您可以使用OrderBy()函数订购列表:

list = list.OrderBy(x => x.ParentKey).ToList();

但使用此功能的结果如下:

key ParentKey
1   Null
3   Null
4   Null
2   1
5   1
8   3
6   4
7   6

答案 1 :(得分:1)

如果您有

列表
public class MyObject{
      int Key {get;set;}
      int ? ParentKey{get;set;}
}

然后对该列表进行排序使用:

 var list = new List<MyObject>(){ new MyObject{ Key = 1 , ParentKey = null } , new MyObject{Key=2 , PatentKey = 1}  /* and so on */};

  var sortedList = list.OrderBy(o=>o.ParentKey , new MyComparer());



public class MyComparer : IComparer<MyObject>
{     
    public int Compare(MyObject o1, MyObject o2)
    {
        if (ol.HasValue && o2.HasValue)
        {
            if (ol.ParentKey.Value == o2.ParentKey.Value)
                 return 0;
            return ol.ParentKey.Value  > o2.ParentKey.Value  ? 1 : -1;
        }
        else
            return 0;

    }
}

这将生成您期望的序列

答案 2 :(得分:0)

我相信你想要实现的是DFS有序的树印 Linq无法帮助你(至少开箱即用)。

我建议在您的数据结构中调整DFS实现。请参阅Eric Lippert's suggestion

相关问题