有没有更短的方法来检查我的随机数从 1 - 100 (catNum) 对照这张动物表?这个看起来还不错,但我还有几个更大的表要处理,我想使用比使用下面的语句所必须的行更少的行:
if (catNum < 36) { category = "Urban"; }
else if (catNum < 51) { category = "Rural"; }
else if (catNum < 76) { category = "Wild"; }
else if (catNum < 86) { category = "Wild Birds"; }
else { category = "Zoo"; }
更多表格的示例:
我更喜欢使用这样的东西而不是许多 if/else
类别类
class Category
{
public int Min { get; set; }
public int Max { get; set; }
public string Name { get; set; }
}
初始化类别一次并用您的值填充它
var categories = new List<Category>();
最后是解析类别的方法
public static string Get(int currentValue)
{
var last = categories.Last(m => m.Min < currentValue);
//if the list is ordered
//or
// var last = categories.FirstOrDefault(m => m.Min <= currentValue && m.Max >= currentValue);
return last?.Name;
}