Browse Source

improve totree method performance

SqlSugar5
liuchao 2 years ago
parent
commit
0f9508897d
  1. 44
      Src/Asp.Net/SqlSugar/Abstract/QueryableProvider/QueryableProvider.cs

44
Src/Asp.Net/SqlSugar/Abstract/QueryableProvider/QueryableProvider.cs

@ -2454,32 +2454,34 @@ namespace SqlSugar
exp = (exp as UnaryExpression).Operand; exp = (exp as UnaryExpression).Operand;
} }
var parentIdName = (exp as MemberExpression).Member.Name; var parentIdName = (exp as MemberExpression).Member.Name;
var result = list.Where(it =>
{
var value = it.GetType().GetProperty(parentIdName).GetValue(it); return BuildTree(list, pk, parentIdName, childName, rootValue)?.ToList() ?? default;
if (rootValue != null) }
{
return value.ObjToString() == rootValue.ObjToString(); private static IEnumerable<T> BuildTree(IEnumerable<T> list, string idName, string pIdName, string childName, object rootValue)
} {
else if (value == null || value.ObjToString() == "" || value.ObjToString() == "0" || value.ObjToString() == Guid.Empty.ToString()) var type = typeof(T);
{ var mainIdProp = type.GetProperty(idName);
return true; var pIdProp = type.GetProperty(pIdName);
} var childProp = type.GetProperty(childName);
else
{ var kvList = list.ToDictionary(x => mainIdProp.GetValue(x).ObjToString());
return false; var group = list.GroupBy(x => pIdProp.GetValue(x).ObjToString());
}
}).ToList(); var root = rootValue != null ? group.FirstOrDefault(x => x.Key == rootValue.ObjToString()) : group.FirstOrDefault(x => x.Key == null || x.Key == "" || x.Key == "0" || x.Key == Guid.Empty.ToString());
if (result != null && result.Count > 0)
if (root != null)
{ {
foreach (var item in result) foreach (var item in group)
{ {
var pkValue = item.GetType().GetProperty(pk).GetValue(item); if (kvList.TryGetValue(item.Key, out var parent))
item.GetType().GetProperty(childName).SetValue(item, GetTreeChildList(list, pkValue, pk, childName, parentIdName)); {
childProp.SetValue(parent, item.ToList());
}
} }
} }
return result;
return root;
} }
public List<T> GetTreeChildList(List<T> alllist, object pkValue, string pkName, string childName, string parentIdName) public List<T> GetTreeChildList(List<T> alllist, object pkValue, string pkName, string childName, string parentIdName)

Loading…
Cancel
Save