Linq-to-XML: Clearing Queries

New to Linq, trying to request an XDocument. I want elements where a certain attribute is one of two values.

Look for suggestions to optimize this query:

query = from xElem in doc.Descendants(StringLiterals._streamNodeName)
where ((0 == xElem.Attribute(StringLiterals._typeAttributeName).Value.CompareTo(StringLiterals._sWorkspace)) ||
(0 == xElem.Attribute(StringLiterals._typeAttributeName).Value.CompareTo(StringLiterals._sNormal)))
select new AccuRevXmlElement
{
_location = xElem.Attribute(StringLiterals._nameAttributeName).Value,
_streamNumber = xElem.Attribute(StringLiterals._streamNumberAttributeName).Value
};


Thanks for any ideas.

0


a source to share


1 answer


You are actually fine, but you can simplify it a bit (untested):

from xElem in doc.Descendants(StringLiterals._streamNodeName)
let typeAttributeValue = xElem.Attribute(StringLiterals._typeAttributeName).Value
where typeAttributeValue == StringLiterals._sW... ||
      typeAttributeValue == StringLiterals._sNormal
select new AccuRevXmlElement
{
    _location = xElem.Attribute(StringLiterals._nameAttributeName).Value,
    _streamNumber =
        xElem.Attribute(StringLiterals._streamNumberAttributeName).Value
};

      



The key differences are the keyword let

, which introduces a new variable within the query, and the fact that you can compare strings using an operator ==

as it System.String

implements that operator.

0


a source







All Articles