Optimized code

This commit is contained in:
sunkaixuan
2024-01-18 05:41:50 +08:00
parent 06803183b3
commit 5d70375d51
2 changed files with 28 additions and 27 deletions

View File

@@ -352,7 +352,7 @@ namespace SqlSugar
{
var childName = ((childListExpression as LambdaExpression).Body as MemberExpression).Member.Name;
string parentIdName = GetParentName(parentIdExpression);
return BuildTree(list, pk, parentIdName, childName, rootValue)?.ToList() ?? default;
return UtilMethods.BuildTree(list, pk, parentIdName, childName, rootValue)?.ToList() ?? default;
}
private static string GetParentName(Expression<Func<T, object>> parentIdExpression)
@@ -366,32 +366,6 @@ namespace SqlSugar
return parentIdName;
}
private static IEnumerable<T> BuildTree(IEnumerable<T> list, string idName, string pIdName, string childName, object rootValue)
{
var type = typeof(T);
var mainIdProp = type.GetProperty(idName);
var pIdProp = type.GetProperty(pIdName);
var childProp = type.GetProperty(childName);
var kvList = list.ToDictionary(x => mainIdProp.GetValue(x).ObjToString());
var group = list.GroupBy(x => pIdProp.GetValue(x).ObjToString());
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 (root != null)
{
foreach (var item in group)
{
if (kvList.TryGetValue(item.Key, out var parent))
{
childProp.SetValue(parent, item.ToList());
}
}
}
return root;
}
public List<T> GetTreeChildList(List<T> alllist, object pkValue, string pkName, string childName, string parentIdName)
{
var result = alllist.Where(it =>

View File

@@ -18,6 +18,33 @@ namespace SqlSugar
{
public class UtilMethods
{
public static IEnumerable<T> BuildTree<T>(IEnumerable<T> list, string idName, string pIdName, string childName, object rootValue)
{
var type = typeof(T);
var mainIdProp = type.GetProperty(idName);
var pIdProp = type.GetProperty(pIdName);
var childProp = type.GetProperty(childName);
var kvList = list.ToDictionary(x => mainIdProp.GetValue(x).ObjToString());
var group = list.GroupBy(x => pIdProp.GetValue(x).ObjToString());
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 (root != null)
{
foreach (var item in group)
{
if (kvList.TryGetValue(item.Key, out var parent))
{
childProp.SetValue(parent, item.ToList());
}
}
}
return root;
}
internal static bool? _IsErrorDecimalString { get; set; }
internal static bool? IsErrorDecimalString()
{