views:

15

answers:

1

Hi,

I am little new to linq and was wondering how i can select the application in the following xml based on the application name using Extension Methods (not using the query expression)

<applicationlist>
<application>
    <name>test1</name>
    <ele1>852</ele1
    <ele2>http://localhost/test1&lt;/ele2&gt;
</application>

<application>
    <name>test2</name>
    <ele1>456</ele1
    <ele2>http://localhost/test2&lt;/ele2&gt;
</application>
</applicationlist>
+1  A: 

Assuming that by "the SQL way of selecting" you mean "using a query expression", let's start off with your query expression:

var v = from b in root.Descendants("application")
      where b.Element("name").Value.Trim().ToLower() == appName.Trim().ToLower()
      select b;

With extension methods, this would just be:

var v = root.Descendants("application")
            .Where(b => b.Element("name").Value.Trim().ToLower() ==
                        appName.Trim().ToLower());

I would recommend against making case-insensitive comparisons this way though - it has cultural problems. Use something like this instead:

var v = root.Descendants("application")
            .Where(b => b.Element("name").Value.Trim().Equals(appName.Trim(),
                                     StringComparison.CurrentCultureIgnoreCase);

(or one of the other StringComparison options - or an instance of StringComparer).

You might also want to trim appName once rather than for every comparison...

Jon Skeet
That is a wonderful explanation. Thanks a lot. Edited my question also to frame it properly.
Amit