Leaving out the max value in an Enumeration This is part of a school assignment and I came up with the following solution to leave out the max value in a Enumeration:

static void Opdracht3()
{
    List&lt;int&gt; values = new List&lt;int&gt;();
    foreach (int value in Enum.GetValues(typeof(Opleidingen)))
    {
        values.Add(value);
    }

    foreach (int value in values)
    {
        if (value != values.Max())
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}


How could I improve this piece of (working) code?
This is not efficient:


foreach (int value in values)
{
    if (value != values.Max())



Because in every iteration, you recalculate values.Max(), when it would be enough to do it once, before starting the loop.

Also, you don't need to create values as a List&lt;int&gt;. As a result, the method can be simplified:

static void Opdracht3()
{
    int maxValue = Enum.GetValues(typeof(Opleidingen)).Cast&lt;int&gt;().Max();

    foreach (int value in Enum.GetValues(typeof(Opleidingen)))
    {
        if (value != maxValue)
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}


And as @blueraja pointed out, to reduce duplication even further, it's good to cache Enum.GetValues(typeof(Opleidingen)).Cast&lt;int&gt;() in a variable:

static void Opdracht3()
{
    int[] values = Enum.GetValues(typeof(Opleidingen)).Cast&lt;int&gt;();
    int maxValue = values.Max();

    foreach (int value in values)
    {
        if (value != maxValue)
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}