你可以用可枚举。聚合为了这个。唉,这个函数会一遍又一遍地计算最小控件的大小。
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();