Nathan Kamenar
Nathan Kamenar

Reputation: 884

Control manipulation with lambda expression

I am trying to get a better grasp of lambda expressions and use it to refactor some code. I have some code that runs on back end page load to find the meta tag where the IE mode is set and change it to edge mode, overriding a SharePoint masterpage just for one specific page. Here is the code I have now that accomplishes this:

foreach (HtmlMeta tag in Page.Header.Controls.OfType<HtmlMeta>())
    {
        if (tag.Content.Contains("IE=", StringComparison.OrdinalIgnoreCase))
        {
            tag.Content = "IE=Edge";
        }
    }

I would like to make this more concise by using a lambda expression but I am having trouble figuring out how exactly to select the relevant tag. Here is what I have so far:

var t = Page.Header.Controls.Cast<Control>().Where(n => n is HtmlMeta);

How can I accomplish the functionality of the first block of code more concisely using lambda expressions?

Upvotes: 0

Views: 205

Answers (1)

har07
har07

Reputation: 89325

Building the query to get list of controls to be updated can be translated into LINQ as follow :

var t = Page.Header.Controls
            .OfType<HtmlMeta>()
            .Where(h => h.Content.Contains("IE=", StringComparison.OrdinalIgnoreCase));

Since LINQ purpose is for query, data modification still need to be done using a looping construct :

foreach (var tag in t)
{
    tag.Content = "IE=Edge";
}

Upvotes: 1

Related Questions