目前我的数据看起来像这样
ID PARENT ID
1 0
2 1
3 2
4 2
5 3
6 5
我想计算与一位父母相关的项目,例如,对ID 1进行计数会返回5,因为
ID 2 has ID 1 as parent
ID 3 has ID 2 as parent, which has ID 1 as parent
ID 4 has ID 2 as parent, which has ID 1 as parent
ID 5 has ID 3 as parent, which has ID 2 as parent, which has ID 1 as parent
ID 6 has...
我使用简单的递归解决了这个问题
private int Count(Entry entry)
{
int cnt = 0;
foreach (Entry foundEntry in AllEntries.Where(x => x.ParentID == entry.ID)) {
cnt++;
cnt += Count(found);
}
return cnt;
}
// somewhere in the code
foreach (Entry currentEntry in AllEntries.Where(x => x.ParentID == 1).ToList()) {
cnt++;
cnt += Count(currentEntry );
}
还有其他不使用递归的方法吗?(LINQ,堆栈..)
如果我正确理解了您的问题,则可以通过以下方式进行遍历AllEntries
并跟踪相关的父母HashSet<int>
:
private int Count(Entry entry)
{
HashSet<int> parentIds = new HashSet<int>();
parentIds.Add(entry.ID);
int count = 0;
foreach (Entry e in AllEntries.OrderBy(x => x.ParentID))
{
if (parentIds.Contains(e.ParentID))
{
count++;
parentIds.Add(e.ID);
}
}
return count;
}
用法:
int count = Count(AllEntries[0]) //where AllEntries[0] = new Entry(){ ID = 1, ParentID = 0 }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句