C#怎么从List集合中随机取出其中一个值

1.首先在该命名空间下创建一个实体,和在Main方法下List集合,为后续做准备:

   /// <summary>
    /// 实体
    /// </summary>
    public class Student { 
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Location { get; set; }
        public string Hobby { get; set; }
    }
       //创建一个List集合
            List<Student> Students = new List<Student>();
            //添加数据
            Students.Add(new Student()
            {
                ID=1,
                Name="猪猪侠",
                Age=12,
                Location="长沙",
                Hobby = "打怪"
            });
            Students.Add(new Student()
            {
                ID = 2,
                Name = "猫咪",
                Age = 15,
                Location = "株洲",
                Hobby = "打球"
            });
            Students.Add(new Student()
            {
                ID = 3,
                Name = "大象",
                Age = 34,
                Location = "邵阳",
                Hobby = "抽血"
            });
            Students.Add(new Student()
            {
                ID = 4,
                Name = "猴子",
                Age = 32,
                Location = "醴陵",
                Hobby = "吃香蕉"
            });
            Students.Add(new Student()
            {
                ID = 5,
                Name = "鸭子",
                Age = 30,
                Location = "山西",
                Hobby = "吃蚯蚓"
            });

 

第一种方法:使用Random随机数区取出其中一个

//创建随机数,并在集合总数中随机取出一个
int r = new Random().Next(Students.Count);
//随机打印输出
Console.WriteLine($"ID:{Students[r].ID}--姓名:{Students[r].Name}");

 

第二种方法:使用GUID进行随机排序。

//使用GUID随机排序找出第一个
Student stu = Students.OrderBy(u => Guid.NewGuid()).First();
//打印输出
Console.WriteLine($"ID:{stu.ID}--姓名:{stu.Name}");

 

C#怎么从List集合中随机取出其中一个值

上一篇:Node Sass does not yet support your current environment: Windows 64-bit


下一篇:02 在Windows系统中创建一个Cordova项目