C
C#2y ago
Indeed

✅ Shorten inline switch with multiple passing values

Hi! Would there be a way to shorten this? In python, their pattern matching would have a simple in [x1,x2,x3]
3 Replies
Indeed
Indeed2y ago
private static WeatherType WeatherCodeToWeatherType(int weatherCode) {
return weatherCode switch {
0 => WeatherType.Clear,
1 or 2 or 3 => WeatherType.PartlyCloudy,
45 or 48 => WeatherType.Fog,
51 or 53 or 55 => WeatherType.Drizzle,
61 or 63 or 65 or 66 or 67 or 80 or 81 or 82 => WeatherType.Rain,
71 or 73 or 75 or 77 or 85 or 86 => WeatherType.Snowfall,
95 or 96 or 99 => WeatherType.Thunderstorm,
_ => WeatherType.Clear
};
}
private static WeatherType WeatherCodeToWeatherType(int weatherCode) {
return weatherCode switch {
0 => WeatherType.Clear,
1 or 2 or 3 => WeatherType.PartlyCloudy,
45 or 48 => WeatherType.Fog,
51 or 53 or 55 => WeatherType.Drizzle,
61 or 63 or 65 or 66 or 67 or 80 or 81 or 82 => WeatherType.Rain,
71 or 73 or 75 or 77 or 85 or 86 => WeatherType.Snowfall,
95 or 96 or 99 => WeatherType.Thunderstorm,
_ => WeatherType.Clear
};
}
Angius
Angius2y ago
Most you could do is, probably
return weatherCode switch {
0 => WeatherType.Clear,
var w when new[]{1, 2, 3}.Contains(w) => WeatherType.PartlyCloudy,
// ...
}
return weatherCode switch {
0 => WeatherType.Clear,
var w when new[]{1, 2, 3}.Contains(w) => WeatherType.PartlyCloudy,
// ...
}
But that hardly shortens the code
Indeed
Indeed2y ago
oh thank you <3, yes it does sadly appear as tho 😦