我的任务是向现有代码库添加功能。代码主要由刚刚离开我们团队的开发人员编写。考虑到这一点,我有一些限制:/。
开发人员之前编写过一些代码,这些代码看起来像List和Tree之间的交叉。在用户界面中,它是一个树形结构。但是,在代码中,它是一个List。有点奇怪。这里定义了两个主要类:
public class TreeBranch
{
public Guid ID { get; set; }
}
public class TreeItem
{
public Guid ID { get; set; }
public Guid TreeBranchID { get; set; }
public Guid? ParentTreeItemID { get; set; }
public int Level { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? MarkedOn { get; set; }
}
因此,TreeBranch存储在数据库表中,TreeItem存储在数据库表中。执行查询,返回具有MarkedOn值为NULL的特定TreeBranchID的所有TreeItem元素。这是处理清单:
List<TreeItem> treeItems = GetTreeBranchItems("someID");
treeItems.Sory(new TreeItemComparer());
My TreeItemComparer类如下所示:
public class TreeItemComparer: IComparer<TreeItem>
{
// allow us to look up parent Items by GUID
IDictionary<Guid, TreeItem> itemLookup;
public TreeItemComparer(IEnumerable<TreeItem> list)
{
itemLookup = list.ToDictionary(item => item.ID);
foreach (var item in list)
SetLevel(item);
}
public int SetLevel(TreeItem item)
{
if ((item.Level == 0) && (item.ParentTreeItemID != Guid.Empty))
{
if (itemLookup.ContainsKey(item.ParentTreeItemID))
item.Level = 1 + SetLevel(itemLookup[item.ParentTreeItemID]);
}
else if (item.ParentTreeItemID == Guid.Empty)
item.Level = 1;
return item.Level;
}
public int Compare(TreeItem x, TreeItem y)
{
// see if x is a child of y
while (x.Level > y.Level)
{
if ((x.ParentTreeItemID == y.ID) || (x.ParentTreeItemID == Guid.Empty))
return 1;
x = itemLookup[x.ParentTreeItemID];
}
// see if y is a child of x
while (y.Level > x.Level)
{
if ((y.ParentTreeItemID == x.ID) || (y.ParentTreeItemID == Guid.Empty))
return -1;
}
// x and y are not parent-child, so find common ancestor
while (x.ParentTreeItemID != y.ParentTreeItemID)
{
if (x.ParentTreeItemID != Guid.Empty)
x = itemLookup[x.ParentTreeItemID];
if (y.ParentTreeItemID != Guid.Empty)
y = itemLookup[y.ParentTreeItemID];
}
// compare createDate of children of common ancestor
return x.CreatedOn.CompareTo(y.CreatedOn);
}
}
此代码有效,但有一个例外。偶尔,我会得到一棵破树。例如,如果我的结构如下所示:
Item 1
Item 1-A (Imagine this TreeItem has a MarkedOn value that is NOT null)
Item 1-A-a
Item 1-A-a-1
Item 1-A-b
Item 1-B
嗯,在上面的示例中,我应该只有以下内容:
Item 1
Item 1-B
然而,我正在
Item 1
Item 1-A-a
Item 1-A-a-1
Item 1-A-b
Item 1-B
我的问题是,带有MarkedOn值的TreeItem和所有它的“子”不应该是集合的一部分。由于我们的环境,我无法触及数据库:(。与此同时,我不知道如何在代码中执行此操作。有没有人有任何想法?
谢谢!
答案 0 :(得分:0)
您可以在从数据库中取回结果后过滤结果。
List<TreeItem> orphanedItems = new List<TreeItem>();
foreach (TreeItem item in results)
{
if (item.ParentTreeItemID != Guid.Empty &&
!results.Any(tree => tree.ID == item.ParentTreeItemID)
{
orphanedItems.Add(item);
}
}
foreach (TreeItem orphan in orphanedItems)
results.Remove(orphan);