Files
juipnet/Infrastructure/Hncore.Infrastructure/Tree/DataNode.cs
“wanyongkang” ed3b2c653e 接口文件
2024-04-10 13:55:27 +08:00

75 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hncore.Infrastructure.Tree
{
public class DataNode<TData>
{
public DataNode(TData data)
{
this.Data = data;
}
public DataNode<TData> Parent { get; set; }
public TData Data { get; set; }
public List<DataNode<TData>> Children { get; set; } = new List<DataNode<TData>>();
public bool IsLeaf { get { return this.Children.Count()==0; } }
public void Traverse(Action<DataNode<TData>> act)
{
act(this);
this.Children.ForEach(item =>
{
item.Traverse(act);
});
}
public string GetFullPath(Func<TData, string> func, string separator = ".")
{
var parent = this.Parent;
var names = new List<string> { func(this.Data) };
while (parent != null)
{
names.Add(func(parent.Data));
parent = parent.Parent;
}
names.Reverse();
return string.Join(separator, names).TrimStart(separator.ToArray());
}
public DataNode<TData> SortAsc<Tkey>(Func<TData, Tkey> exp)
{
if (this.Children.Count > 0)
{
Func<DataNode<TData>, Tkey> iierExp = m => exp(m.Data);
this.Children.OrderBy(iierExp);
this.Children.ForEach(item =>
{
item.SortAsc(exp);
});
}
return this;
}
public DataNode<TData> SortDesc<Tkey>(Func<TData, Tkey> exp)
{
if (this.Children.Count > 0)
{
Func<DataNode<TData>, Tkey> iierExp = m => exp(m.Data);
this.Children.OrderByDescending(iierExp);
this.Children.ForEach(item =>
{
item.SortDesc(exp);
});
}
return this;
}
}
}