Get Max value from List

后端 未结 8 435
猫巷女王i
猫巷女王i 2021-02-02 05:08

I have List List, my type contains Age and RandomID

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

What

8条回答
  •  名媛妹妹
    2021-02-02 05:28

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

    public int FindMaxAge(List 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(List list, Converter 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;
    }
    

    You can use this with:

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

    Or you could use LINQBridge :)

    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));
    }
    

提交回复
热议问题