c# - 如果对于随机数 C#.net,则替代 else

标签 c# if-statement random

<分区>

有没有更短的方法来检查我的随机数从 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"; }

更多表格的示例:

example of larger tables

最佳答案

我更喜欢使用这样的东西而不是许多 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;
}

关于c# - 如果对于随机数 C#.net,则替代 else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49142506/

相关文章:

c# - 对两个List<>的操作

c - if else 语句双重打印 C

php - 生成没有这些字符的随 secret 码 "l1o0"

perl - 在 Perl 中打乱数组的最佳方法是什么?

c++ - Python 在 C++ 中的 random.uniform()?

c# - 如何在钢笔绘制的形状中填充颜色

c# - MySql alter table in c# 错误

c# - 发出异步休息请求

python - 将 random.choice 与 if/elif/else 语句一起使用

java - 我怎样才能避免这个 if 语句