3

拥有这两个类和这个 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可能的关键字?

4

1 回答 1

1

是时候递归了!只需包装获取的函数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);

函数调用的第一次加载使用空字符串作为类别名称,因为我们不需要过滤结果。然后我们递归调用相同的函数,但按类别名称过滤。试试看,对我有用。

于 2012-08-31T11:16:57.850 回答