2017-10-10 14 views
0

私は属性を持つ次の表がありますObjectsComponentsが含まれているElementsが含まれている): 表はとしてネストレベルが含まれているなど、IdParentIdNameネストされた行を入れ子レベルで並べ替えるにはどうすればよいですか?

Id | Parent | Name 
--------------------------------------- 
1 | NULL | Name (this is object 1)  
2 | 1  | Name (this is element 1) 
3 | 2  | Name (this is component 1) 
4 | 2  | Name (this is component 2) 
5 | 2  | Name (this is component 3) 
6 | 1  | Name (this is element 2) 
7 | 6  | Name (this is component 4) 
8 | 1  | Name (this is element 3) 
9 | NULL | Name (this is object 2) 
10 | 9  | Name (this is element 4) 
11 | 10  | Name (this is component 5) 
12 | 10  | Name (this is component 6) 

この結果を提示する表のように単一のLINQクエリが必要です。

私はnested for loopsを使用してオブジェクトを取得し、次に各オブジェクトがその要素を取得し、次に各要素がそのコンポーネントを取得するのを嫌います - 同じことはテーブルの再帰のためです。

答えて

0

1つのlinq文には適切ではありません。再帰的方法を使用してください:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 


namespace ConsoleApplication7 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DataTable dt = new DataTable(); 
      dt.Columns.Add("Id", typeof(int)); 
      dt.Columns.Add("Parent", typeof(int)); 
      dt.Columns.Add("Name", typeof(string)); 

      dt.Rows.Add(new object[] { 1, null, "Name (this is object 1)" }); 
      dt.Rows.Add(new object[] { 2, 1, "Name (this is element 1)" }); 
      dt.Rows.Add(new object[] { 3, 2, "Name (this is component 1)" }); 
      dt.Rows.Add(new object[] { 4, 2, "Name (this is component 2)" }); 
      dt.Rows.Add(new object[] { 5, 2, "Name (this is component 3)" }); 
      dt.Rows.Add(new object[] { 6, 1, "Name (this is element 2)" }); 
      dt.Rows.Add(new object[] { 7, 6, "Name (this is component 4)"}); 
      dt.Rows.Add(new object[] { 8, 1, "Name (this is element 3)" }); 
      dt.Rows.Add(new object[] { 9, null, "Name (this is object 2)" }); 
      dt.Rows.Add(new object[] { 10, 9, "Name (this is element 4)" }); 
      dt.Rows.Add(new object[] { 11, 10, "Name (this is component 5)" }); 
      dt.Rows.Add(new object[] { 12, 10, "Name (this is component 6)" }); 

      Node.RecursiveFill(dt, null, Node.root); 

     } 

    } 
    public class Node 
    { 
     public static Node root = new Node(); 

     public List<Node> children { get; set; } 
     public int id { get; set; } 
     public string name { get; set; } 

     public static void RecursiveFill(DataTable dt, int? parentId, Node parentNode) 
     { 
      foreach (DataRow row in dt.AsEnumerable().Where(x => x.Field<int?>("Parent") == parentId)) 
      { 
       Node newChild = new Node(); 
       if (parentNode.children == null) parentNode.children = new List<Node>(); 
       parentNode.children.Add(newChild); 
       newChild.id = row.Field<int>("Id"); 
       newChild.name = row.Field<string>("Name"); 
       RecursiveFill(dt, newChild.id, newChild); 
      } 
     } 
    } 

} 
関連する問題