Create a hierarchical class structure, cycle through the data table, and then add the parent, child, and return object

I am really new to C #

I want to create a class structure that can represent the following hierarchical structure of objects of all the same types

-Parent1
- - Child1 
- - - ChildA of Child1
- - - ChildB of Child1
- - Child2 
- - - ChildA of Child2
- - - ChildB of Child2
- Parent2

Data lines have ID, ParentID, name and level.

Level

equal to O for parent, 1 for children 1, 2 for ChildA, etc.

I can return the data from the database to datatable, but after that I’m afraid any help on creating the class structure and then filling the object would be greatly appreciated

+3
source share
2 answers

, LINQ. sampe. , 0.

var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(Int32));
dataTable.Columns.Add("ParentId", typeof(Int32));
dataTable.Columns.Add("Name", typeof(String));
dataTable.Rows.Add(new Object[] { 1, 0, "A" });
dataTable.Rows.Add(new Object[] { 2, 1, "B" });
dataTable.Rows.Add(new Object[] { 3, 1, "C" });
dataTable.Rows.Add(new Object[] { 4, 0, "D" });
dataTable.Rows.Add(new Object[] { 5, 4, "E" });

:

class Item {

  public Int32 Id { get; set; }

  public String Name { get; set; }

  public IEnumerable<Item> Children { get; set; }

}

:

IEnumerable<DataRow> GetChildren(DataTable dataTable, Int32 parentId) {
  return dataTable
    .Rows
    .Cast<DataRow>()
    .Where(row => row.Field<Int32>("ParentId") == parentId);
}

, . :

Item CreateItem(DataTable dataTable, DataRow row) {
  var id = row.Field<Int32>("Id");
  var name = row.Field<String>("Name");
  var children = GetChildren(dataTable, id)
    .Select(r => CreateItem(dataTable, r))
    .ToList();
  return new Item { Id = id, Name = name, Children = children };
}

:

IEnumerable<DataRow> GetTopLevelRows(DataTable dataTable) {
  return dataTable
    .Rows
    .Cast<DataRow>()
    .Where(row => row.Field<Int32>("ParentId") == 0);
}

:

var items = GetTopLevelRows(dataTable)
  .Select(row => CreateItem(dataTable, row))
  .ToList();
+9

, .

public class MyItem
{
  public IList<MyItem> ChildItems{get;set;}
}

, , , , MyItem .

:

var parentItem = new MyItem()
var childItem = new MyItem();
var childChildItem = new MyItem();

childItem.ChildItems.Add(childChildItem);
parentItem.ChildItems.Add(childItem);

, , .

+2

All Articles