asp.net 使用Enumerable.OfType()或LINQ查找特定类型的所有子控件< T>

46qrfjad  于 2022-11-19  发布在  .NET
关注(0)|答案(4)|浏览(155)

现有的MyControl1.Controls.OfType<RadioButton>()搜索仅通过初始收集,不进入子级。
是否可以使用Enumerable.OfType<T>()LINQ找到特定类型的所有子控件,而无需编写自己的递归方法?例如this

tcbh2hod

tcbh2hod1#

我使用一个扩展方法来扁平化控件层次结构,然后应用过滤器,所以这是使用自己递归方法。
方法如下所示

public static IEnumerable<Control> FlattenChildren(this Control control)
{
  var children = control.Controls.Cast<Control>();
  return children.SelectMany(c => FlattenChildren(c)).Concat(children);
}
tquggr8v

tquggr8v2#

我使用这个通用递归方法:
这个方法的假设是,如果控件是T,则该方法不会查看其子控件。如果您也需要查看其子控件,则可以轻松地相应更改它。

public static IList<T> GetAllControlsRecusrvive<T>(Control control) where T :Control 
{
    var rtn = new List<T>();
    foreach (Control item in control.Controls)
    {
        var ctr = item as T;
        if (ctr!=null)
        {
            rtn.Add(ctr);
        }
        else
        {
            rtn.AddRange(GetAllControlsRecusrvive<T>(item));
        }

    }
    return rtn;
}
1qczuiv0

1qczuiv03#

要改进上述答案,将返回类型更改为

//Returns all controls of a certain type in all levels:
public static IEnumerable<TheControlType> AllControls<TheControlType>( this Control theStartControl ) where TheControlType : Control
{
   var controlsInThisLevel = theStartControl.Controls.Cast<Control>();
   return controlsInThisLevel.SelectMany( AllControls<TheControlType> ).Concat( controlsInThisLevel.OfType<TheControlType>() );
}

//(Another way) Returns all controls of a certain type in all levels, integrity derivation:
public static IEnumerable<TheControlType> AllControlsOfType<TheControlType>( this Control theStartControl ) where TheControlType : Control
{
   return theStartControl.AllControls().OfType<TheControlType>();
}
zlhcx6iw

zlhcx6iw4#

12年后,我喜欢这个答案(https://stackoverflow.com/a/2209896/1039753),并希望按照KeithS的建议,构建一个选项来传递类型约束,以便只返回所需的控件类型。

扩展方法

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyApp.Extensions
{
    public static class ControlExtensions
    {
        public static IEnumerable<Control> FlattenChildren<T>(this Control control)
        {
            return control.FlattenChildren().OfType<T>().Cast<Control>();
        }

        public static IEnumerable<Control> FlattenChildren(this Control control)
        {
            var children = control.Controls.Cast<Control>();
            return children.SelectMany(c => FlattenChildren(c)).Concat(children);
        }
    }
}

示例用法

已添加到窗体的_Load事件...

//Show the name of each ComboBox on a form (even nested controls)
foreach (ComboBox cb in this.FlattenChildren<ComboBox>())
{
    Debug.WriteLine(cb.Name);
}

//Get the number of controls on a form
Debug.WriteLine("Control count on form: " + this.FlattenChildren().Count());

相关问题