我有父母子女关系的数据,发现给定父母的所有孩子都是直接使用Linq,但我有其他问题,在提供孩子时找到所有父母.
Listelements = new List { new FlatData {Id = 1, ParentId = NULL ,Text = "Apple"}, new FlatData {Id = 2, ParentId = 1, Text = "Cat"}, new FlatData {Id = 3, ParentId = 2, Text = "Dog"}, new FlatData {Id = 4, ParentId = 3, Text = "Elephant"} };
当给出Id 4时,我需要能够反向遍历并使用LINQ(lambda表达式)查找所有父项,非常感谢任何帮助.
您可以使用递归来执行以下操作:
private IEnumerableFindAllParents(List all_data, FlatData child) { var parent = all_data.FirstOrDefault(x => x.Id == child.ParentId); if (parent == null) return Enumerable.Empty (); return new[] {parent}.Concat(FindAllParents(all_data, parent)); }
并像这样使用它:
int id = 4; var child = elements.First(x => x.Id == id); var parents = FindAllParents(elements, child).ToList();
这个解决方案有效,但是如果你有一个大的数据集,那么你应该考虑使用a Dictionary
来更快地获取FlatData
给定的对象Id
.
以下是该方法在这种情况下的样子:
private IEnumerableFindAllParents(Dictionary all_data, FlatData child) { if(!all_data.ContainsKey(child.ParentId)) return Enumerable.Empty (); var parent = all_data[child.ParentId]; return new[] {parent}.Concat(FindAllParents(all_data, parent)); }
以下是您将如何使用它:
var dictionary = elements.ToDictionary(x => x.Id); //You need to do this only once to convert the list into a Dictionary int id = 4; var child = elements.First(x => x.Id == id); var parents = FindAllParents(dictionary, child).ToList();