【问题标题】:Linq Fetch all controls (ordered)Linq 获取所有控件(有序)
【发布时间】:2010-10-12 06:43:51
【问题描述】:

有没有办法使用 linq 获取所有控件。

我想做的是这样的(按标签索引排序控件):

foreach (Control control in this.Controls.OrderBy(c => c.TabIndex)
{
    ...
}

当我得到一个列表时,我会使用这种查询<...>

我使用 c# 和 .Net 3.5

【问题讨论】:

    标签: c# .net linq .net-3.5


    【解决方案1】:

    ControlCollection 仅实现 IEnumerable,而不是 IEnumerable&lt;T&gt;。不过这很容易解决 - 添加对 Cast() 的调用:

    foreach (Control control in Controls.Cast<Control>()
                                        .OrderBy(c => c.TabIndex))
    {
    }
    

    或者您可以使用查询表达式,它会在必要时调用Cast()

    var controls = from Control c in Controls
                   orderby c.TabIndex
                   select c;
    
    foreach (Control control in controls)
    {
    }
    

    【讨论】:

    • 注意:TabIndex 在 WebControl 上,所以将所有“Control”替换为“WebControl”。
    • TabIndex 也在 WinControl 上。谢谢你的快速回答!
    猜你喜欢
    • 2013-04-18
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多