简体   繁体   English

使用Lambda表达式进行控件操纵

[英]Control manipulation with lambda expression

I am trying to get a better grasp of lambda expressions and use it to refactor some code. 我试图更好地理解lambda表达式并将其用于重构一些代码。 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. 我有一些在后端页面加载时运行的代码,以查找设置了IE模式的meta标签并将其更改为边缘模式,从而仅针对一个特定页面覆盖SharePoint母版页。 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. 我想通过使用lambda表达式来使其更加简洁,但是我在弄清楚如何准确选择相关标签方面遇到了麻烦。 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? 如何使用lambda表达式更简洁地完成第一段代码的功能?

Building the query to get list of controls to be updated can be translated into LINQ as follow : 生成查询以获取要更新的控件列表可以转换为LINQ,如下所示:

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 : 由于LINQ的目的是查询,因此仍然需要使用循环构造来完成数据修改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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