记录转化为有层次结构的树状列表的通用算法
问题说明: |
| |
---|---|---|
解决方法: |
|
public class CollectionHelper
{
private static ArrayList Fill(int pID, int level, ArrayList list)
{
ArrayList returnList = new ArrayList();
foreach(object obj in list)
{
int typePID = (int)ReflectionUtil.GetProperty(obj, "PID");
int typeID = (int)ReflectionUtil.GetProperty(obj, "ID");
string typeName = ReflectionUtil.GetProperty(obj, "Name") as string;
if(pID == typePID)
{
string newName = new string('-', level * 4) + typeName;
ReflectionUtil.SetProperty(obj, "Name", newName);
returnList.Add(obj);
returnList.AddRange(Fill(typeID, level+1, list));
}
}
return returnList;
}
/// <summary>
/// 生成有层次结构的列表
/// </summary>
/// <param name="list">具有Name,ID,PID成员的任何集合</param>
/// <returns></returns>
public static ArrayList GetTreeItems(ArrayList list)
{
return Fill(-1, 0, list);
}
}
{
private static ArrayList Fill(int pID, int level, ArrayList list)
{
ArrayList returnList = new ArrayList();
foreach(object obj in list)
{
int typePID = (int)ReflectionUtil.GetProperty(obj, "PID");
int typeID = (int)ReflectionUtil.GetProperty(obj, "ID");
string typeName = ReflectionUtil.GetProperty(obj, "Name") as string;
if(pID == typePID)
{
string newName = new string('-', level * 4) + typeName;
ReflectionUtil.SetProperty(obj, "Name", newName);
returnList.Add(obj);
returnList.AddRange(Fill(typeID, level+1, list));
}
}
return returnList;
}
/// <summary>
/// 生成有层次结构的列表
/// </summary>
/// <param name="list">具有Name,ID,PID成员的任何集合</param>
/// <returns></returns>
public static ArrayList GetTreeItems(ArrayList list)
{
return Fill(-1, 0, list);
}
}
public sealed class ReflectionUtil
{
private ReflectionUtil()
{ }
public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
fi.SetValue(obj, value,null);
}
public static object GetProperty(object obj, string name)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
return fi.GetValue(obj,null);
}
}
{
private ReflectionUtil()
{ }
public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
fi.SetValue(obj, value,null);
}
public static object GetProperty(object obj, string name)
{
PropertyInfo fi = obj.GetType().GetProperty(name, bf);
return fi.GetValue(obj,null);
}
}
效果图如下
专注于代码生成工具、.Net/.NetCore 框架架构及软件开发,以及各种Vue.js的前端技术应用。著有Winform开发框架/混合式开发框架、微信开发框架、Bootstrap开发框架、ABP开发框架、SqlSugar开发框架等框架产品。
转载请注明出处:撰写人:伍华聪 http://www.iqidi.com
转载请注明出处:撰写人:伍华聪 http://www.iqidi.com