LINQ “Any” Keyword to check for existence of an element/attribute


One of the things you must do when writing a LINQ to Xml query definition is check for the existence of nonrequired elements and attributes before using them. For instance, a client application displays an image of the book in the ListBox control. The source URL of the image is grabbed from the SmallImage element’s URL element. If the SmallImage element does not exist, which is certainly a possibility if there is no image on record, the LINQ query definition must account for this.

For example,

<Item>
    <SmallImage>
        <URL>
            
        </URL>
    </SmallImage>
</Item>

 

Before grabbing a value, you can perform a simple check to make sure the element exists; you do this by checking the Elements collection’s Any method. The Any method returns a Boolean value that indicates whether the collection contains elements. If the element exists, you can grab the value of the element. If the element does not exist you can set alternatives. The following shows the logic that checks for the existence of the image’s URL; if it is found it grabs the value and sets it to the imageSource variable.

let imageSource = (book.Elements(ns + "SmallImage").Any()
    ? book.Element(ns + "SmallImage").Element(ns + "URL").Value
    : string.Empty)
p.s. for more on the usage of the keyword let, take a look at https://vincenthomedev.wordpress.com/2007/12/19/linq-let-keyword/
 
Advertisements

5 thoughts on “LINQ “Any” Keyword to check for existence of an element/attribute

  1. We are a group of volunteers and starting
    a new scheme in our community. Your web site provided
    us with valuable info to work on. You have done an impressive job and our whole community will be thankful to you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s