selecting an element in xml using linq extension methods

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</ele2>
</application>

<application>
    <name>test2</name>
    <ele1>456</ele1
    <ele2>http://localhost/test2</ele2>
</application>
</applicationlist>

Answers


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...


Need Your Help

Remove a specific filter in a Kendo Grid with toolbar template

javascript c# jquery asp.net telerik

I have a Telerik Kendo Grid with a toolbar template for create personalized filters.

Add web font (FoundIcons) inside input text element

css zurb-foundation

I would like to add an icon (magnifying-glass) inside an input box used for site content searching.