这可能只是一些逻辑问题..或我的设计问题,目前有障碍,以保持跟踪功能,以保持跟踪层次
我有一个自定义的team类
public class Team
{
public int PositionID;
public int? LeaderId;
public List<Team> Members = new List<Team>();
public Team(int positionid, int? leaderid)
{
PositionID = positionid;
LeaderId= leaderid;
}
} 生成的数据以树形式呈现,类似于节点是一个列表

下面是我用来获取直接领导者的函数
public static Team GetChildNode(List<Team> nodes, int seekId)
{
Team found = null;
//store leaders of leader that lead to the seek leader.
List<Team> Leaders= new List<Team>();
foreach (Team node in nodes)
{
if (found == null)
{
if (node.PositionID == seekId)
{
found = node;
return found;
}
else
{
if (node.Members.Count > 0)
{
return GetChildNode(node.Members, seekId);
}
}
}
}
return found;
}目前,返回值将根据数据返回给我一个有或没有成员的团队。
在调试时,我注意到使用上面的逻辑,我似乎碰到了
return GetChildNode(node.Members, seekId);即使在找到节点之后..
我想跟踪导航..
换句话说,这个函数返回给我的是直接的前导。
我希望得到直接领导者>直到主要领导者(领导者没有领导者)
我不介意返回一个列表,其中列表的最小索引0是主要引导者,最大索引是直接引导者
发布于 2014-01-15 03:35:30
我建议为IEnumarable编写扩展类。
static class EnumerableExtension
{
public static IEnumerable<IEnumerable<TSt>> FindNodes<T,TSt>(this IEnumerable<T> source, Func<T, IEnumerable<T>> childrenSelector, Func<T,TSt> resultSelector, Func<T, bool> predicate)
{
var result = new List<List<TSt>>();
Action<T, List<TSt>> search = null;
search = (element, resultStruct) =>
{
resultStruct.Add(resultSelector(element));
if (predicate(element))
{
result.Add(resultStruct);
}
else
{
foreach (var item in childrenSelector(element))
{
search(item,new List<TSt>(resultStruct));
}
}
};
foreach (var v in source)
{
search(v, new List<TSt>());
}
return result;
}
}第一个参数是团队的源列表,第二个参数是您类型的子节点的选择器,第三个参数是结果的选择器(例如liderId ),第四个参数是过滤条件(例如liderId)。它具有足够的通用性,您可以为不同的方法包装函数。用法:将返回导航到leaderId为100的团队的leaderId列表
teams.FindNodes(children => children.Members, res => res.LeaderId, con => con.LeaderId == 100);https://stackoverflow.com/questions/21109831
复制相似问题