从List< myType>获取最大值 [英] Get Max value from List<myType>

查看:50
本文介绍了从List< myType>获取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表List<MyType>,我的类型包含AgeRandomID

I have List List<MyType>, my type contains Age and RandomID

现在,我想从此列表中找到最大年龄.

Now I want to find the maximum age from this list.

最简单,最有效的方法是什么?

What is the simplest and most efficient way?

推荐答案

好的,因此,如果您没有LINQ,则可以对其进行硬编码:

Okay, so if you don't have LINQ, you could hard-code it:

public int FindMaxAge(List<MyType> list)
{
    if (list.Count == 0)
    {
        throw new InvalidOperationException("Empty list");
    }
    int maxAge = int.MinValue;
    foreach (MyType type in list)
    {
        if (type.Age > maxAge)
        {
            maxAge = type.Age;
        }
    }
    return maxAge;
}

或者您可以编写一个更通用的版本,可在许多列表类型中重复使用:

Or you could write a more general version, reusable across lots of list types:

public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
{
    if (list.Count == 0)
    {
        throw new InvalidOperationException("Empty list");
    }
    int maxValue = int.MinValue;
    foreach (T item in list)
    {
        int value = projection(item);
        if (value > maxValue)
        {
            maxValue = value;
        }
    }
    return maxValue;
}

您可以将其用于:

// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });

// C# 3
int maxAge = FindMaxValue(list, x => x.Age);

或者您可以使用 LINQBridge :)

在每种情况下,如果需要,都可以通过简单调用Math.Max来返回if块.例如:

In each case, you can return the if block with a simple call to Math.Max if you want. For example:

foreach (T item in list)
{
    maxValue = Math.Max(maxValue, projection(item));
}

这篇关于从List&lt; myType&gt;获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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