【发布时间】:2015-05-26 18:48:40
【问题描述】:
我有一个数据表,我需要在其中将其解析为一组可管理的类数据。在大多数情况下,这并不是一项艰巨的任务,但是,我需要将这些自定义类中的项目组合在一起以使它们有意义。
类
public Parent
{
Parent(){ }
public int ParentID = 0;
public string Name = string.Empty;
public List<Children> Child = new List<Children>();
}
public Children
{
public Children() { }
public string ChildID = 0;
public string Name = string.Empty;
public List<string> ChildBooks = new List<string>();
}
表格
Parent ID | Parent | Child ID | Child | Books
1 | John | 4 | Suzy | Grapes of...
1 | John | 4 | Suzy | Huck........
1 | John | 5 | James | The adven...
2 | Sally | 4 | Suzy | Grapes of...
2 | Sally | 4 | Suzy | Huck........
2 | Sally | 5 | James | The adven...
结果
List<Parent> First index would be
Name: John
Child: 4 Suzy, 5 James
Second index would be
Name: Sally
Child: 4 Suzy (Grapes of..., Huck.....) 5 James (The adven...)
有没有更简单的方法来实现这一点?我当前的方法涉及获取每个Distinct ParentID,将它们链接回子级并在那里创建类。我还没有编写这部分代码,但如果这是唯一的方法,那很好。我只是希望 LINQ 中有一些东西可以帮助我实现我的目标。
【问题讨论】:
-
为什么
John的子 ID 为 4 和 5?在 DataTable 中,两个孩子都是 4?其他记录也是如此。 -
@RahulSingh 输入错误。现已更正。
标签: c# linq class datatable datatables