2017-10-16 43 views
0

我有一个实体:在数据库多级分层数据排序C#

public class Document 
{ 
    public int id; 
    public int? ParentId; 
    public string name; 
} 

和数据:

id | ParentId | name 
----------------------- 
1 |   | fruits 
2 |   | vegetables 
3 |  2  | tomatoes 
4 |  1  | apples 
5 |  4  | golden apples 
6 |  4  | red apples 

或者,如C#:

var documents = new[] 
{ 
    new Document() { id = 1, ParentId = null, name = "fruits" }, 
    new Document() { id = 2, ParentId = null, name = "vegetables" }, 
    new Document() { id = 3, ParentId = 2, name = "tomatoes" }, 
    new Document() { id = 4, ParentId = 1, name = "apples" }, 
    new Document() { id = 5, ParentId = 4, name = "golden apples" }, 
    new Document() { id = 6, ParentId = 4, name = "red apples" }, 
}; 

我需要得到:

id | ParentId | name 
----------------------- 
1 |   | fruits 
4 |  1  | apples 
5 |  4  | golden apples 
6 |  4  | red apples 
2 |   | vegetables 
3 |  2  | tomatoes 

我如何在c#中快速排序分层数据?

+1

按哪个列排序? –

+1

你的班'文件'不能代表你提供的数据。 'ParentId'必须是'int?'或者你的数据必须对每一行都有一个值。请提供您的输入数据作为有效的C#代码。 – Enigmativity

+2

呵呵,你的类def是无效的C#。你应该尽力让我们尽可能地容易回答。 – Enigmativity

回答

2

因此,考虑到:

public class Document 
{ 
    public int id; 
    public int? ParentId; 
    public string name; 
} 

和:

var documents = new[] 
{ 
    new Document() { id = 1, ParentId = null, name = "fruits" }, 
    new Document() { id = 2, ParentId = null, name = "vegetables" }, 
    new Document() { id = 3, ParentId = 2, name = "tomatoes" }, 
    new Document() { id = 4, ParentId = 1, name = "apples" }, 
    new Document() { id = 5, ParentId = 4, name = "golden apples" }, 
    new Document() { id = 6, ParentId = 4, name = "red apples" }, 
}; 

然后这个工程:

var lookup = documents.ToLookup(x => x.ParentId); 

Func<int?, IEnumerable<Document>> heirarchySort = null; 
heirarchySort = pid => 
    lookup[pid].SelectMany(x => new[] { x }.Concat(heirarchySort(x.id))); 

IEnumerable<Document> sorted = heirarchySort(null); 

它给你:

Sorted Documents