C# 递归数据表中的子对象
我有下表C# 递归数据表中的子对象,c#,C#,我有下表 PNLParentId id operator 12 13 * 12 14 * 12 15 * 12 1 - 12 2 - 13 21 / 13 20 / 我想获得每个不同操作员的ID树 如何更改以下代码?
PNLParentId id operator
12 13 *
12 14 *
12 15 *
12 1 -
12 2 -
13 21 /
13 20 /
我想获得每个不同操作员的ID树如何更改以下代码?我已经为此工作了几个小时,任何帮助都将不胜感激
var q= from p in TypedDataTable
where p.ParentID == null // well get all parents
select new
{
ParentID = p.ParentID,
child = from c in TypedDataTable
where c.ParentID == p.ID select
new {ChildID=c.ID,
ParentID = c.ParentID}
};
我更喜欢使用一个类来存储数据(如果使用LINQ to SQL之类的东西,您可能已经自动生成了这些数据):
注意:尚不清楚什么是
typedDataable
或它的定义位置。我假设它是全局可用的,如果不是,那么您将希望将它作为参数传递给GetItems
函数。您需要什么结果?@SWeko我希望获得相同的parentid和oprator,所有儿童都需要进一步治疗。。。这是同一个问题吗??
class TypedItem
{
public int ID {get;set;}
public int ParentID {get;set;}
public List<TypedItem> Children {get;set;}
public TypedItem()
{
Children = new List<TypedItem>();
}
}
List<TypedItem> GetItems(int? parentId)
{
var results = from p in TypedDataTable
where p.ParentID == parentId
select new TypedItem(){
ID = p.ID,
ParentID = p.ParentID
};
foreach(var result in results)
{
result.Children = GetItems(result.ID);
}
return results.ToList();
}
var items = GetItems(null);