no9 no9 - 12 days ago 5x
C# Question

LINQ question ... need to get element with min value

Im new to linq so i still struggle ....

I have a collection of controls (each has a Location of type Point).
I need to remove the control with the lowest Y value (top control) from the collection.

An example would be most appreciated !


Something like this:

collection.Remove(collection.OrderBy(c => c.Location.Y).First());

The ordering is quite expensive, so depending on your use-case you could also find the item with the lowest value and then remove it:

collection.Remove(collection.First(c => c.Y == collection.Min(c2 => c2.Y)));

This enumerates the list up to three times, generally this should still be faster than the OrderBy, but if performance is important to you then measure first.