【问题标题】:Matching randomly generated number to object properties将随机生成的数字与对象属性匹配
【发布时间】:2020-07-12 10:44:30
【问题描述】:

我有一个随机数生成器,最大值,最小值如下所示,是否可以识别对象属性(在我的情况下为 int ID)是否与生成的随机数匹配? 还是有另一种方法可以让我从集合中“随机”选择一个对象?

随机数生成器是:

private readonly Random _random = new Random();
public int RandomNumber(int min, int max)
{
   return _random.Next(min, max);
}

我希望从位于集合中的对象中进行选择,例如:

public class Staff
{
     public int ID;
     public Staff(int ID)
     {
         ID = this.ID
     }
     static void Main(string[] args)
     {
         List<Staff> StaffList = new List<Staff>();
         StaffList.Add(new Staff(6);
     }
}

任何建议表示赞赏

【问题讨论】:

    标签: c# c#-3.0


    【解决方案1】:

    首先你需要修复你的构造函数,你得到了向后的赋值

        public Staff(int ID)
        {
            this.ID = ID;
        }
    

    这是您从列表中获取随机项目的方式:

    var randomStaffItem = StaffList[RandomNumber(0, StaffList.Count)];
    

    【讨论】:

      【解决方案2】:

      Lev 在从您的列表中随机选择一个 Staff 实例时给出了一个很好的答案。

      你还问过:

      ... 是否可以识别对象属性(我的 int ID case) 匹配生成的随机数?

      您可以使用Any() 来确定该ID 是否存在。如果您需要实际匹配的实例,则可以改用FirstOrDefault()。他们都收到了predicate in the form of a lamba expression

      同时使用Any()FirstOrDefault() 的示例如下:

      class Program
      {
      
          private static readonly Random _random = new Random();
          public static int RandomNumber(int min, int max)
          {
              return _random.Next(min, max);
          }
      
          static void Main(string[] args)
          {
              List<Staff> StaffList = new List<Staff>();
              for(int i=1; i<=10; i++)
              {
                  StaffList.Add(new Staff(i));
              }
      
              int rndID = RandomNumber(1, 21); // 1 to 20 inclusive
              Console.WriteLine("Random ID: " + rndID.ToString());
      
              var StaffExists = StaffList.Any(s => s.ID == rndID);
              if (StaffExists)
              {
                  Console.WriteLine("There does exist a staff member with an ID of " + rndID.ToString());
              }
              else
              {
                  Console.WriteLine("There does NOT exist a staff member with an ID of " + rndID.ToString());
              }
      
              var StaffMatch = StaffList.FirstOrDefault(s => s.ID == rndID);
              if (StaffMatch != null)
              {
                  Console.WriteLine("Match found: " + StaffMatch.ID.ToString());
              }
              else
              {
                  Console.WriteLine("No match found.");
              }
      
              Console.Write("Press Enter to Quit");
              Console.ReadLine();
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 2018-03-10
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多