【发布时间】:2017-08-04 23:06:21
【问题描述】:
我有一个对象,它可以包含自己类型的列表。例如,一个项目类包含各种属性。另一个类,ItemSet 包含一个项目列表,但也可以有一个嵌套的项目集。换句话说,一个 ItemSet 可以包含其他项目集。如下所示:
public class Item
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public int Property3 { get; set; }
public int Property4 { get; set; }
}
public class ItemSet
{
public List<Item> Items { get; set; }
//.
//.
//.
//.
public List<ItemSet> ItemSets { get; set; }
}
我一直在兜圈子(哈哈,明白了吗?)试图弄清楚如何循环遍历 ItemSet 对象。我一直无法适应父子集的无限可能性。我觉得我做这件事比它需要的要困难得多。
ItemSets = getItemSets(....);
bool hasSets = false;
ItemSet currentItemSet;
foreach(ItemSet itemSet in currentItemSets)
{
currentItemSet = itemSet;
hasSets = HasSets(currentItemSet);
if(hasSets == false)
{
//do stuff with currentItemSet
}
while(hasSets == true)
{
List<ItemSet> SubSets = getItemSets(CurrentItemSet);
foreach(subset in SubSets)
{
currentItemSet = subset;
//do stuff with currentItemSet
hasSets = HasSets(currentItemSet);
??????????????????????????
}
}
}
我知道我在这里很差,但希望得到一些指示。我确实需要能够辨别 Itemset 是否包含子子集并正确处理。
【问题讨论】:
-
或许考虑递归?
标签: c# loops foreach while-loop