Find max value of two (or more) properties in list

感情迁移 提交于 2021-01-27 05:58:50

问题


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?


回答1:


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?)




回答2:


An alternative solution using LINQ if you need more than 2 properties (which is the limit of Math.Max):

int max = list
  .SelectMany(elem => new[]{ elem.Prop1, elem.Prop2, elem.Prop3 })
  .Max();


来源:https://stackoverflow.com/questions/13816094/find-max-value-of-two-or-more-properties-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!