Find max value of two (or more) properties in list
c#, linq, list, max
Solution
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?)
Problem
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?