在列表中找到两个(或更多)属性的最大值 [英] Find max value of two (or more) properties in list

查看:37
本文介绍了在列表中找到两个(或更多)属性的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SO上已经以一种或另一种方式提出了这个问题,但并非如此.我刚遇到一个非常基本的问题,当时我正在寻找一种统计解决方案:-)我得到了具有两个整数属性的对象列表.现在,我想在列表中找到所有对象的两个属性的最大值.
我想出了三种解决方案:

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:

第一种方法:

int max = Math.Max(list.Max(elem => elem.Nr), list.Max(elem => elem.OtherNr));

第二种方法:

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.

还有其他解决方案吗?

推荐答案

如果愿意

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.

(而且,您是否不需要从 double 到其中的某个地方的 int 进行强制转换?)

(Also, don't you need a cast from double to int somewhere in there?)

这篇关于在列表中找到两个(或更多)属性的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆