c# - 需要获取新选定元素的上下文(可能是像 'this' 这样的关键字?)

标签 c# linq xml-parsing

有这两个类和这个 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);

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

关于c# - 需要获取新选定元素的上下文(可能是像 'this' 这样的关键字?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12213939/

相关文章:

C# + DirectShow.NET = 简单的网络摄像头访问?

javascript - Windows Phone 8 Web 浏览器不运行 javascript

c# - 使用 JavaScript 将 visible 属性设置为 false 时删除空白区域

c# - 如何向 LINQ 查询添加额外的行?

java - 根据 XSD 验证完整的 XML

javascript - 如何按元素内容过滤已解析的 XML 数据 [jQuery]

c# - 如何从 xelement 中提取 cdata 的值?

c# - "Already Exists"使用 CSOM 获取 SharePoint 2013 库项目时引发异常

c# - 使用 LINQ 按多个属性分组并求和

c# - 在 Entity Framework 中选择类别树