【问题标题】:Linq Query OptimizationLinq 查询优化
【发布时间】:2013-02-05 12:53:47
【问题描述】:

如何优化此查询并转换为 lambda ?

XElement xde = new XElement("Elements", (from a in rootElement.Elements("Class")
                   where a.Attribute("Location").Value.Equals("FirstFloor") 
                   select (from b in a.Elements("Subject")
                           where b.Attribute("Notify").Value.Equals("001")
                           select b.Elements())));

【问题讨论】:

标签: c# xml linq lambda linq-to-xml


【解决方案1】:

就性能而言,我认为您的查询无法优化。

但是,您可以将 Equals 替换为 == 并删除不必要的 select,使其更具可读性

XElement xde =
        new XElement("Elements", (from a in rootElement.Elements("Class")
                                  where a.Attribute("Location").Value == "FirstFloor"
                                  from b in a.Elements("Subject")
                                  where b.Attribute("Notify").Value == "001"
                                  select b.Elements()));

【讨论】:

    【解决方案2】:

    您可以简单地将节点大小写为string,而不是读取节点的值。因此,如果您的 xml 中缺少属性,您将避免异常。另外我建议您使用与元素名称相对应的范围变量名称(更好的可读性):

    XElement xde =
        new XElement("Elements",  
             from c in rootElement.Elements("Class")
             where (string)c.Attribute("Location") == "FirstFloor"
             from s in c.Elements("Subject")
             where (string)s.Attribute("Notify") == "001"
             select s.Elements());
    

    考虑也使用 XPath(所有查询都适合一行):

    new XElement("Elements", rootElement
     .XPathSelectElements("Class[@Location='FirstFloor']/Subject[@Notify='001']/*"));
    

    Lambda(你也想要方法语法):

    new XElement("Elements", 
        rootElement.Elements("Class")
                   .Where(c => (string)c.Attribute("Location") == "FirstFloor")
                   .Elements("Subject")
                   .Where(s => (string)s.Attribute("Notify") == "001")
                   .Elements());
    

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2022-12-13
      相关资源
      最近更新 更多