使用 C# lamda 表达式写的两种递归函数

it2022-05-05  149

使用 C# lamda 表达式写的两种递归函数

//将一个平行数据,整理为一个树形数据 private void Test1(List<myType> allTypeList) {   //查找父节点  List<myType> rootType = allTypeList.Where(o => o.ParentId == -1).ToList();   //递归主函数  Action<myType> addChildType = null;  addChildType   = (typeInfo =>      {       var childInfo = allTypeList.Where(o => o.ParentId == typeInfo.id);       if (childInfo.IsNullOrDbNull())        return;       childInfo.All(        o =>         {          typeInfo.ChildTypes.Add(o);          addChildType(o);          return true;         });      });   //递归调用  allTypeList.ForEach(   o =>    {     addChildType(o);    }); }

//递归查找指定节点的完整路径 private void Test2(string id) {  List<myType> crumbs = new List<myType>();  //递归查询指定 id 的完整路径,arg1=待查询id,arg2=子节点集合,arg3=父节点信息  Func<string, List<myType>, myType> getTypeFullPath = null;  getTypeFullPath   = (     (id, childList) =>      {       foreach (var child in childList)       {        if (childList.IsNullOrDbNull())         return null;

       if (child.id.ToString().Equals(id))        {         return child;        }        if (child.ChildTypes.Count > 0)        {         var result = getTypeFullPath(id, child.ChildTypes);         if (!result.IsNullOrDbNull())         {          //result.id 和 result.Name 是 myType 类的属性字段          crumbs.Add(new myType() {Id = result.id, Name = result.Name});          return child;         }        }       }       return null;      });

  //递归入口  myType typeinfo = = getTypeFullPath(threeLevelType, productTypeList);   //这里返回的是一级节点  if (!typeinfo.IsNullOrDbNull())  {   crumbs.Add(new myType() { Id = typeinfo.id.ToString(), Name = typeinfo.TypeName });  }

 return crumbs; }

 

转载保留:http://write.blog.csdn.net/postedit/7873644

 

 

 

转载于:https://www.cnblogs.com/xxj-jing/archive/2012/08/16/2890055.html

相关资源:各显卡算力对照表!

最新回复(0)