简体   繁体   English

使用Linq C#进行类搜索或更新的嵌套列表

[英]Nested List Of Class Search Or Update Using Linq C#

How can I find class from nested list ? 如何从嵌套列表中找到课程?

I am working on trees and just want to retreive and add child based on id. 我正在树上工作,只是想撤退并根据id添加孩子。

Class

 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; }
}

Object Creation and Query 对象创建和查询

 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

You need to use recursion. 您需要使用递归。 Try next code 尝试下一个代码

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;
}

Use SelectMany 使用SelectMany

 t.children.SelectMany(s => s.children)
  .FirstOrDefault(s => s.children.Any(d => d.id == 3));

Using a recursive method will resolve your problem. 使用递归方法将解决您的问题。

    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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM