C#怎麼從List集合中隨機取出其中一個值

滔滔程式設計師發表於2020-10-08

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}");

 

相關文章