Reputation: 31
How can I refactor this code to avoid repeating myself? Especially if there are a lot more cases! I've read about simplifying select cases with a dictionnary but I don't see how I could use that in this case. Any suggestions?
Dim sPath As String = String.Empty
Dim aThing As Decimal
Select Case True
Case (aThing < 7.5)
sPath = "~/images/Grafik_7.5.png"
Case (aThing >= 7.5 AndAlso aThing < 8.75)
sPath = "~/images/Grafik_18.75.png"
Case (aThing >= 58.75 AndAlso aThing < 60)
sPath = "~/images/Grafik_60.png"
Case (aThing >= 60 AndAlso aThing < 61.25)
sPath = "~/images/Grafik_61.25.png"
Case (aThing >= 61.25 AndAlso aThing < 62.5)
sPath = "~/images/Grafik_62.5.png"
Case (aThing >= 62.5 AndAlso aThing < 63.75)
sPath = "~/images/Grafik_63.75.png"
Case (aThing >= 63.75 AndAlso aThing < 65)
sPath = "~/images/Grafik_65.png"
Case (aThing >= 65 AndAlso aThing < 66.25)
sPath = "~/images/Grafik_66.25.png"
Case (aThing >= 66.25)
sPath = "~/images/Grafik_67.5.png"
End Select
Upvotes: 2
Views: 133
Reputation: 101072
Using a dictionary, you could do it like this:
Dim conditions = new Dictionary(of Predicate(of Double), String) From
{
{Function(a) a < 7.5, "Grafik_7.5.png"},
{Function(a) a >= 7.5 AndAlso a <= 8.75, "Grafik_8.75.png"},
{Function(a) a >= 58.75 AndAlso a < 60, "Grafik_60.png"}
}
Dim aThing = 8.3
Dim result = conditions.Single(Function (c) c.Key(aThing)).Value
But note that dictionaries are not sorted, so make sure that there is only ever a single function that returns True for any given value.
Another way would be to create the filename dynamically, like this:
Dim sizes = new List(Of Double) From {7.5, 8.75, 60, 61.25}
Dim InvC = System.Globalization.CultureInfo.InvariantCulture
DIm size = sizes.First(Function(s) s > aThing).ToString(InvC)
Dim result = "Grafik_" + size + ".png"
Upvotes: 4
Reputation: 54427
This may need to change slightly depending on what the maximum numerical value can be but I'm thinking something like this:
Dim values = {7.5D, 18.75D, 60D, 61.25D} 'etc.
Dim value = values.First(Function(x) x > aThing)
sPath = $"~images/Grafik_{value}.png
Upvotes: 1