代码之家  ›  专栏  ›  技术社区  ›  serhio

LINQ表达式优化语法?

  •  3
  • serhio  · 技术社区  · 15 年前
    foreach (var item in mainCanvas.Children)
    {
        if (item is Button)
        {
            (item as Button).Content = "this is a button";
        }                
    }
    

    我是否可以使用LINQ或.NET4的其他功能使其更简洁(也许性能更好)?

    5 回复  |  直到 15 年前
        1
  •  12
  •   Mark Byers    15 年前

    你可以用 Enumerable.OfType

    foreach (var button in mainCanvas.Children.OfType<Button>())
    {
        button.Content = "this is a button";
    }
    

    性能测量

    方法1 :OPs原始建议

    foreach (var item in mainCanvas.Children)
    {
        if (item is Button)
        {
            (item as Button).Content = "this is a button";
        }                
    }
    

    方法2

    foreach(var按钮输入主画布。子对象。OfType<按钮>())
    {
    

    方法3 :仅铸造一次

    foreach (var item in mainCanvas.Children)
    {
        Button button = item as Button;
        if (button != null)
        {
            button.Content = "this is a button";
        }                
    }
    

    :for循环:

    List<object> children = mainCanvas.Children;
    for (int i = 0; i < children.Count; ++i)
    {
        object item = children[i];
        if (item is Button)
        {
            (item as Button).Content = "this is a button";
        }                
    }
    

    Iterations per second
    
    Method 1: 18539180
    Method 2:  7376857
    Method 3: 19280965
    Method 4: 20739241
    

    结论

    • 最大的改进可以通过使用一个简单的 for foreach .
    • 只铸造一次也可以稍微提高性能。
    • 使用 OfType 速度要慢得多。

    但请记住,首先要优化可读性,只有当您对性能进行了分析并发现此特定代码是性能瓶颈时,才能优化性能。

        2
  •  3
  •   danijels    15 年前

    mainCanvas.Children.OfType<Button>.ToList().ForEach(b => b.Content = "this is a button");
    
        3
  •  1
  •   Cheng Chen    15 年前

    OfType<T> 分机。

    foreach (var item in mainCanvas.Children.OfType<Button>()) 
    { 
        item.Content = "this is a button"; 
    }
    

    如果没有,可以使用:

    foreach (var item in mainCanvas.Children.Where(item=>item is Button).Cast<Button>()) 
    { 
        item.Content = "this is a button"; 
    }
    
        4
  •  1
  •   Judah Gabriel Himango    15 年前

    并不是说它特别优越,但这种语法有一些优点:

    使用LINQ和Microsoft ReactiveExtensions 框架,

    mainCanvas.Children
       .OfType<Button>()
       .Do(b => b.Content = "I'm a button!")
       .Run();
    
        5
  •  1
  •   csharpstudent    13 年前

    要仅迭代集合中的实际按钮,可以执行以下操作:

    foreach(Button button in mainCanvas.Children)
         button.Content = "this is a button";
    

    据我所知,这是转换成上述方法4的语法。但别引用我的话。(编辑:我的意思是方法3)