C# 使用Linq C搜索或更新类的嵌套列表#
如何从嵌套列表中查找类 我正在树上工作,只想检索和添加基于id的子对象 课程C# 使用Linq C搜索或更新类的嵌套列表#,c#,linq,tree,C#,Linq,Tree,如何从嵌套列表中查找类 我正在树上工作,只想检索和添加基于id的子对象 课程 public class d3_mitch { public int id { get; set; } public string name { get; set; } public string type { get; set; } public string description { get; set; } public List<d3_mitch> c
public class d3_mitch
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string description { get; set; }
public List<d3_mitch> children { get; set; }
}
公共类d3\u mitch
{
公共int id{get;set;}
公共字符串名称{get;set;}
公共字符串类型{get;set;}
公共字符串说明{get;set;}
公共列表子项{get;set;}
}
对象创建和查询
d3_mitch t = new d3_mitch();
t.id = 1;
t.type = "Root";
t.name = "Animal";
t.description = "A living organism that feeds on organic matter";
t.children = new List<d3_mitch>() {
new d3_mitch() { name = "Carnivores", type = "Type", id = 2, description = "Diet consists solely of animal materials",
children=new List<d3_mitch>(){ new d3_mitch() { id= 3 ,name="Felidae",type="Family",description="Also known as cats"} }
}
};
d3_mitch child = t.children.Where(x => x.id == 3).FirstOrDefault();
//This return null because no direct child has has id = 3 but nested
d3_-mitch t=新的d3_-mitch();
t、 id=1;
t、 type=“Root”;
t、 name=“动物”;
t、 description=“以有机物为食的活生物体”;
t、 children=新列表(){
新的d3_mitch(){name=“肉食动物”,type=“type”,id=2,description=“饮食仅由动物材料组成”,
children=new List(){new d3_mitch(){id=3,name=“Felidae”,type=“Family”,description=“也称为cats”}
}
};
d3_mitch child=t.children.Where(x=>x.id==3.FirstOrDefault();
//此返回值为null,因为没有id=3但嵌套的直接子级
使用SelectMany
t.children.SelectMany(s => s.children)
.FirstOrDefault(s => s.children.Any(d => d.id == 3));
您需要使用递归。尝试下一个代码
d3_mitch FindById(d3_mitch root, int id)
{
if (root.id == id)
return root;
foreach (var child in root.children)
{
if (child.id == id)
return child;
var subTreeResult = FindById(child, id);
if (subTreeResult != null)
return subTreeResult;
}
// no such item
return null;
}
使用递归方法将解决您的问题
public static d3_mitch Find(d3_mitch main, int id)
{
if (main.id == id)
return main;
if (main.id != id && main.children != null)
{
foreach (var child in main.children)
{
return child.children.Any(x=>x.id==id)? child.children.First(x=>x.id==id) : Find(child, id);
}
}
return null;
}
抱歉,这不是类的数组,这就是为什么不能实现“SelectMany”的原因。不,它不起作用,因为嵌套的子级也可能有嵌套的子级等等。正确分析代码。它确实工作正常!你测试过了吗?我添加了很多记录,如果没有具有该id的项目,你的代码将始终返回第一个孩子,那么它就会工作。如果根本没有子节点,则始终返回根元素,无论其id是否匹配,都不能在
foreach
循环中执行return Find
。如果我们要找的东西是第二个孩子呢?将结果存储在局部变量中,若它具有非空值,则我们已找到所需项并可以返回它。如果没有,请继续使用修复程序循环编辑响应