Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# GUI优化嵌套foreach_C#_Wpf - Fatal编程技术网

C# GUI优化嵌套foreach

C# GUI优化嵌套foreach,c#,wpf,C#,Wpf,由于性能低下,有人可以在以下WPF GUI上帮助您如何转换为Linq: foreach (Grid b in main_grid.Children) { foreach (Control s in b.Children) { if (s.GetType() == typeof(Button)) { if (s.Tag.ToString() == message) { i

由于性能低下,有人可以在以下WPF GUI上帮助您如何转换为Linq:

foreach (Grid b in main_grid.Children)
{
    foreach (Control s in b.Children)
    {
        if (s.GetType() == typeof(Button))
        {
            if (s.Tag.ToString() == message)
            {
                if (status == "OIRS_INUSE")
                {
                    s.Background = Brushes.Orange;
                }
                else
                {
                    s.Background = defaultBackground;
                }
            }
        }
    }
}

首先,你问错了问题。林克帮不了忙

加速此循环的一种方法是减少其瓶颈的工作负载:

foreach (Grid b in main_grid.Children)
{
    foreach (Control s in b.Children)
    {
        if (s.SomeEnumValue == SomeEnum.Value)
        {
            s.Background = Brushes.Orange;
        }
        else
        {
            s.Background = defaultBackground;
        }
    }
}
第一次比较
如果(s.GetType()==typeof(按钮))

您的速度将比简单的字段比较慢5倍以上

第二次比较
if(s.Tag.ToString()==message)
和第三次比较
status==“OIRS\u INUSE”

此外,第二个比较包含一个ToString方法,它有自己的成本


因此,摆脱所有这些昂贵的比较,用简单的字段比较代替它们,例如便宜的枚举。

“由于性能低下,如何转换为LINQ?”?为什么您认为LINQ会产生更好的性能?LINQ仍然需要为每个人做一个
s
。到目前为止你做了什么?LINQ对你的表现没有帮助
s。GetType()==typeof(Button)
可以是
s is Button
我想回答这个问题。我有更多的优化。请投票重新打开。
Control
是否有名为
SomeEnumValue
的属性?LINQ的
类型是否有用?为什么您认为
var
可以避免强制转换?还是说演员阵容很昂贵?@DStanley多亏了你的评论,我发现foreach(收藏中的ExplicitType项目)
一点也不贵。我删除了答案的最后一部分。@mjwills我建议OP使用更好的比较,而不是解析和比较字符串,因此
SomeEnumValue
可以是任何东西,例如标记或自定义属性。我还删除了关于避免强制转换的部分(请看我上面的评论),这样就可以使用类型为的
,但不会加快速度,因为它仍然会单独应用于每个元素,就像在循环内部一样
for 100 million calls:

typeof(Test): 2756ms
TestType (field): 1175ms
test.GetType(): 3734ms