从下面的代码中,我想过滤并希望只获取MasterproductID = 1
它及其下的子代。通过过滤MasterproductID = 2
和MasterproductID = 3
. 我可以知道该怎么做吗?谢谢你的帮助。
class TreeNode
{
public int MasterProductId;
public int? ParentId;
}
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TreeNode>{
new TreeNode{ MasterProductId = 1 },
new TreeNode{ MasterProductId = 4, ParentId = 1 },
new TreeNode{ MasterProductId = 7, ParentId= 4 },
new TreeNode{ MasterProductId = 5, ParentId = 1 },
new TreeNode{ MasterProductId = 6, ParentId = 1 },
new TreeNode{ MasterProductId = 2 },
new TreeNode{ MasterProductId = 7, ParentId = 2 },
new TreeNode{ MasterProductId = 8, ParentId= 7 },
new TreeNode{ MasterProductId = 3 },
};
foreach (var item in Level(list, null, 0))
{
if (item.Value == 0)
{
Response.Write(String.Format("<b>MasterProductId={0}, Level={1}", item.Key, item.Value) + "</b><br />");
}
else
{
Response.Write(String.Format("MasterProductId={0}, Level={1}", item.Key, item.Value) + "<br />");
}
}
}
private static IEnumerable<KeyValuePair<int, int>> Level(List<TreeNode> list, int? parentId, int lvl)
{
return list
.Where(x => x.ParentId == parentId)
.SelectMany(x =>
new[] { new KeyValuePair<int, int>(x.MasterProductId, lvl) }.Concat(Level(list, x.MasterProductId, lvl + 1))
);
}