This question has been asked in one or the other way on SO but not like this. I just came over a very basic issue where I was looking for a statisfying solution :-)
I got a list of objects which have two integer properties. Now I want to find the max value of both properties of all object in the list.
I came up with three solutions:
First approach:
int max = Math.Max(list.Max(elem => elem.Nr), list.Max(elem => elem.OtherNr));
Second approach:
public int Max(List<Thing> list)
{
int maxNr = 0;
foreach (var elem in list)
{
if (elem.Nr > maxNr)
maxNr = elem.Nr;
if (elem.OtherNr > maxNr)
maxNr = elem.OtherNr;
}
return maxNr;
}
A third approach would be to do the sorting by both attribute and then just take the first entry and get the one or the other property.
I would like to find the fastest way to do this. So of all approaches I like the second one the post (from the performace point of view). Even though the first one is shorter you have to go through the list twice.
Any other solutions?
If you do
int max = list.Max(elem => Math.Max(elem.Nr, elem.OtherNr));
it's still a single-liner but only iterates through the list once. I'd take the single-linedness over the probable slight reduction in efficiency from writing it out by hand.
(Also, don't you need a cast from double
to int
somewhere in there?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With