Dandy Dandy - 2 years ago 102
Vb.net Question

How to get lowest location of controls in array using linq

how to get lowest location of controls in array using linq

i have array of controls say
dim oClipboard() as control

i needed the control which has lowest location or minimum location value from tha oclipboard

so far i have tried linq with min function

Dim p = c.Select(Function(g) g.Location).Min.ToString
Dim x = c.Select(Function(g) g).Min(Function(h) h.Location)

both of above give me error stated below

System.ArgumentException was unhandled
Message=At least one object must implement IComparable.
at System.Collections.Comparer.Compare(Object a, Object b)
at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y)
at System.Linq.Enumerable.Min[TSource](IEnumerable`1 source)
at System.Linq.Enumerable.Min[TSource,TResult](IEnumerable`1 source, Func`2 selector)

is there any way i could get control whhich has lowest location

Answer Source

If by lowest location you mean the control which has shortest Euclidean distance to the (0,0) point you could use the Aggregate extension method:

Control[] oClipboard = ...;
Control control = oClipboard.Aggregate((curMin, c) => (curMin == null || Math.Sqrt(c.Location.X * c.Location.X + c.Location.Y * c.Location.Y) < Math.Sqrt(curMin.Location.X * curMin.Location.X + curMin.Location.Y * curMin.Location.Y) ? c : curMin));

or if you just want to find the control with smallest Y coordinate:

Control control = oClipboard.Aggregate((curMin, c) => (curMin == null || c.Location.Y < curMin.Location.Y ? c : curMin));

Now all that's left for you as an exercise is to translate this to VB.NET.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download