patterncsharpModerate
Leaving out the max value in an Enumeration
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:
How could I improve this piece of (working) code?
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:
Because in every iteration, you recalculate
Also, you don't need to create
And as @blueraja pointed out, to reduce duplication even further, it's good to cache
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.