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

如何从控件数组中获得面积最小的控件?

  •  2
  • Michael  · 技术社区  · 6 年前

    Control[] controls = getControls();
    

    我需要用最小的面积来控制。我知道我可以这样排序并在索引0中获得控制权:

    var min = filtered.OrderBy(x => x.Height * x.Width).ToArray()[0]; 
    

    但是我怎么能在没有命令控件的情况下获取它呢?

    2 回复  |  直到 6 年前
        1
  •  1
  •   41686d6564    6 年前

    你可以用可枚举。聚合为了这个。唉,这个函数会一遍又一遍地计算最小控件的大小。

    Controls 并返回最小的一个,与所有其他linq函数类似。看到了吗 extension methods demystified

    // extension function: gets the size of a control
    public static int GetSize(this Control control)
    {
        return (control.Height * control.Width);
    }
    
    // returns the smallest control, by size, or null if there isn't any control
    public static Control SmallestControlOrDefault(this IEnumerable<Control> controls)
    {
        if (controls == null || !controls.Any()) return null; // default
    
        Control smallestControl = controls.First();
        int smallestSize = smallestControl.GetSize();
    
        // check all other controls if they are smaller
        foreach (var control in controls.Skip(1))
        {
            int size = control.GetSize();
            if (size < smallestSize)
            {
                 smallestControl = control;
                 smallestSize = size;
            }
        }
        return smallestControl;
    }
    

    Skip(1) 将再次迭代第一个元素。如果您不想这样做,请使用 GetEnumerator MoveNext :

    var enumerator = controls.GetEnumerator();
    if (enumerator.MoveNext())
    {   // there is at least one control
        Control smallestControl = enumerator.Current;
        int smallestSize = smallestControl.GetSize();
    
        // continue enumerating the other controls, to see if they are smaller
        while (enumerator.MoveNext())
        {   // there are more controls
            Control control = enumerator.Current;
            int size = control.GetSize();
            if (size < smallestSize)
            {   // this control is smaller
                smallestControl = control;
                smallestSize = size;
            }
        }
        return smallestControl;
    }
    else
    {   // empty sequence
        ...
    }
    

    用法:

    IEnumerable<Control> controls = ...
    Control smallestControl = controls.SmallestControlOrDefault();
    
        2
  •  3
  •   Selmir    6 年前

    这要归功于非常强大但未充分利用的 Aggregate

    var min = controls.Aggregate((x, y) => x.Height * x.Width < y.Height * y.Width ? x : y);
    

    你可以延长你的时间 Control 用一个 Area 属性以避免 方法。