2017-10-16 71 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