Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 !

like image 919
no9 Avatar asked Aug 26 '10 12:08

no9


1 Answers

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.

like image 118
Simon Steele Avatar answered Nov 15 '22 20:11

Simon Steele