Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ递归地添加父级_C#_.net_Linq_Extension Methods - Fatal编程技术网

C# 使用LINQ递归地添加父级

C# 使用LINQ递归地添加父级,c#,.net,linq,extension-methods,C#,.net,Linq,Extension Methods,我为MenuItem定义了以下类 public class MenuItem { public int Id { get; set; } public string Key { get; set; } public int ParentId { get; set; } public string Url { get; set; } } 下面是所有菜单项的集合 List<MenuItem> allMenu=new List&l

我为MenuItem定义了以下类

public class MenuItem
{
    public int Id { get; set; }
    public string Key { get; set; }     
    public int ParentId { get; set; }
    public string Url { get; set; }        
}
下面是所有菜单项的集合

List<MenuItem> allMenu=new List<MenuItem>
  {new MenuItem{Id=1,Key="Level1-A",Url="url1"},
  {new MenuItem{Id=2,Key="Level1-B",Url="url2"},
  {new MenuItem{Id=3,Key="Level2-A",Url="url3", ParentId=1},
  {new MenuItem{Id=4,Key="Level3-AA",Url="url1", ParentId=3}};
//但我还需要包括所有父id菜单项。

在这种情况下,
Level2-A
Level1-A

我怎样才能将此包含在C#中?欢迎使用LINQ或任何扩展方法

List all=new List();
List<MenuItem> all = new List<MenuItem>();
all.Add(item);

while (item.ParentId != 0) // Ideally you should use Nullable<int>
{
    var parent = allMenu.Single(m => m.Id = item.ParentId);
    all.Add(parent);
    item = parent;
}
全部。添加(项目); while(item.ParentId!=0)//理想情况下应该使用Nullable { var parent=allMenu.Single(m=>m.Id=item.ParentId); 全部。添加(父级); 项目=父项; }

但这将导致对数据库的多个查询。如果不希望发生这种情况,则需要编写自己的SQL查询,并使用数据库功能,如更改菜单项,使其具有可为空的parentId:

public class MenuItem
{
    public int Id { get; set; }
    public string Key { get; set; }
    public int? ParentId { get; set; }
    public string Url { get; set; }
}
使用以下命令获取节点:


我不明白为什么会产生多个查询。我已加载列表中的所有菜单项。我想递归地获取匹配的菜单项及其所有父项,包括它们的父项。@Billa-如果你已经在内存中加载了所有内容,当然你不需要额外访问数据库。
public class MenuItem
{
    public int Id { get; set; }
    public string Key { get; set; }
    public int? ParentId { get; set; }
    public string Url { get; set; }
}
var allMenus=new List<MenuItem>
    {new MenuItem{Id=1,Key="Level1-A",Url="url1"},
    new MenuItem{Id=2,Key="Level1-B",Url="url2"},
    new MenuItem{Id=3,Key="Level2-A",Url="url3", ParentId=1},
    new MenuItem{Id=4,Key="Level3-AA",Url="url1", ParentId=3}};

// Creates trees based on Id and ParentId, 
// in this case there are 2 trees, the second with only item with Id 2
var rootNode = Node<MenuItem>.CreateTree(allMenus, m => m.Id, m => m.ParentId).First();

var targetNode = rootNode.Descendants.Single(n => n.Value.Id == 4);
// Get the values of the ancestors (all the parents and their parents)
var ancestorValues = targetNode.Ancestors.Values();