简体   繁体   中英

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?

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM