HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Leaving out the max value in an Enumeration

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enumerationtheleavingvaluemaxout

Problem

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 values = new List();
    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?

Solution

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. As a result, the method can be simplified:

static void Opdracht3()
{
    int maxValue = Enum.GetValues(typeof(Opleidingen)).Cast().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() in a variable:

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

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

Code Snippets

foreach (int value in values)
{
    if (value != values.Max())
static void Opdracht3()
{
    int maxValue = Enum.GetValues(typeof(Opleidingen)).Cast<int>().Max();

    foreach (int value in Enum.GetValues(typeof(Opleidingen)))
    {
        if (value != maxValue)
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}
static void Opdracht3()
{
    int[] values = Enum.GetValues(typeof(Opleidingen)).Cast<int>();
    int maxValue = values.Max();

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

Context

StackExchange Code Review Q#62228, answer score: 10

Revisions (0)

No revisions yet.