tags:

views:

137

answers:

1

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

Looking for suggestions on how to streamline 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.

A: 

Actually you are quite well underway but you can streamline it a little (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 let keyword that introduces a new variable inside the query and the fact that you can compare strings using the == operator since System.String implements this operator.

Ronald Wildenberg
Much better, and I learned about the let keyword...Does 'let' behave like 'var', where the variable gets its type from the rhs?Thanks for the reply.
Number8
Yes, let behaves like var
Ronald Wildenberg