在VB.net中使用Linq获取节点的所有子节点
我在VB.Net中使用分层数据表填充树列表,如下所示:在VB.net中使用Linq获取节点的所有子节点,vb.net,linq,hierarchical-data,Vb.net,Linq,Hierarchical Data,我在VB.Net中使用分层数据表填充树列表,如下所示: ID ParentID Name ---------------------- 1 NUll a 2 NUll b 3 2 c 4 1 d 5 3 e 6 5 f 7 6 g 8 5 h 我的问题: 如何在vb.net中
ID ParentID Name
----------------------
1 NUll a
2 NUll b
3 2 c
4 1 d
5 3 e
6 5 f
7 6 g
8 5 h
我的问题:
如何在vb.net中使用Linq获取节点(ID)的所有子节点的列表?
请帮帮我。不幸的是,我对VB的了解不够好,不能给你一个VB的答案。我会用C来回答。你可能会理解这个想法。也许你可以添加你的VB翻译 您忘了描述节点类。我想你不仅想要孩子,还想要孙子(等等) 字典中的每个元素都具有与parentId相等的键,并且作为元素包含具有此parentId的所有人员
TreeNode CreateNodeForPerson(Person person)
{
IEnumerable<Person> children = dictionary[person.Id];
IEnumerable<TreeNode> childNodes = children
.Select(child => CreateNodeforPerson(child));
return new TreeNode()
{
Id = person.Id,
Name = person.Name,
Nodes = childNodes,
};
}
TreeNode CreateNodeForPerson(个人)
{
IEnumerable children=字典[person.Id];
IEnumerable childNodes=子节点
.Select(child=>CreateNodeforPerson(child));
返回新的TreeNode()
{
Id=person.Id,
Name=person.Name,
节点=子节点,
};
}
您将看到相同的递归。但是一旦你有了字典,你就不必枚举整个Person集合,你只需要访问你为之创建nod的人的children/children's children等
public static IEnumerable<TreeNode> AsTreeNodes(this IEnumerable<Person> persons)
{
// Top TreeNodes: all persons without a Parent:
return persons.AsTreeNodes((int?)null);
}
public static IEnumerable<TreeNode> AsTreeNodes(this IEnumerable<Person> persons, int? parentId)
{
// Top Nodes: all persons with parentId
var personsWithParentId = persons.Where(person.ParentId == parentId);
foreach (var person in personsWithParentId)
{
// every person will become one TreeNode with sub-nodes using recursion
TreeNode node = new TreeNode()
{
Id = person.Id,
Name = person.Name,
// get all my Children and Children's children:
Nodes = persons.ToNodeCollection(person.Id),
};
yield return node;
}
}
IEnumerable<Person> allPersons = ...
IEnumerable<TreeNode> allFamilyHierarchies = allPersons.AsTreeNodes();
IEnumerable<TreeNode> washingtonFamily = allFamilyHierarchies
.Where(familyHierarchy => familyHierarchy.Name == "George Washington");
var personsWithSameParentId = persons.GroupBy(person => person.ParentId);
var dictionary = personsWithSameParentId.ToDictionary(group => group.Key)
TreeNode CreateNodeForPerson(Person person)
{
IEnumerable<Person> children = dictionary[person.Id];
IEnumerable<TreeNode> childNodes = children
.Select(child => CreateNodeforPerson(child));
return new TreeNode()
{
Id = person.Id,
Name = person.Name,
Nodes = childNodes,
};
}