拥有这两个类和这个linq请求:
var cats = from c in xml.Descendants("category")
let categoryName = c.Attribute("name").Value
let descendants = c.Descendants()
select new Category
{
Name = categoryName,
Items = from d in descendants
let typeId = d.Attribute("id").Value
select new Item
{
Id = typeId,
Name = d.Value,
Category = ???????
}
};
class Category
{
string Name;
IEnumerable<Item> Items;
}
class Item
{
string Id;
string Name;
Category Category;
}
如何将项目的类别影响到当前选定的类别?可能是像this
这样的关键词?
递归的时间到了!只需包装得到Category
的函数,然后在需要时调用它。
public static IQueryable<Category> GetCategories(string catName, XDocument xml)
{
var cats = from c in xml.Descendants("category")
let categoryName = c.Attribute("name").Value
let descendants = c.Descendants()
where (catName == "" || categoryName == catName)
select new Category
{
Name = categoryName,
Items = from d in descendants
let typeId = d.Attribute("id").Value
select new Item
{
Id = typeId,
Name = d.Value,
Category = GetCategories(categoryName, xml).FirstOrDefault()
}
};
return cats.AsQueryable();
}
你这样称呼它:
XDocument xml = XDocument.Parse(...); // parse the xml file
IQueryable<Category> cats = GetCategories("", xml);
函数调用的第一次加载使用空字符串作为类别名称,因为我们不需要过滤结果。然后我们递归地调用相同的函数,但按类别名称进行过滤。试试看,对我有用。