【发布时间】:2020-12-29 00:24:46
【问题描述】:
我有两种方法。在第一个中,我将项目添加到名为 Persons 的列表中。在第二个中,我需要从列表中选择一个随机项目 (Persons) 并从列表中返回人的姓名。
我不确定如何执行此操作。我尝试生成一个随机数和一个随机字母,但我不明白如何将它们与列表一起使用。
任何帮助将不胜感激!提前谢谢你
static void PopulatePersons()
{
Person Bill = new Person("Bill", "no", "brown", 'm');
Person Eric = new Person("Eric", "yes", "brown", 'm');
Person Robert = new Person("Robert", "no", "blue", 'm');
Person George = new Person("George", "yes", "brown", 'm');
Person Herman = new Person("Herman", "no", "green", 'm');
Person Anita = new Person("Anita", "no", "blue", 'f');
Person Maria = new Person("Maria", "yes", "green", 'f');
Person Susan = new Person("Susan", "no", "brown", 'f');
Person Claire = new Person("Claire", "yes", "brown", 'f');
Person Anne = new Person("Anne", "no", "brown", 'f');
Persons = new List<Person>()
{ Bill, Eric, Robert, George, Herman, Anita, Maria, Susan, Claire, Anne };
}
static Person GetRandomPerson()
{
PopulatePersons();
}
【问题讨论】:
-
docs.microsoft.com/pt-br/dotnet/api/system.random?view=net-5.0 只需创建一个 Randon,将 intervalo 设置为 0... List.Count 并用作索引 list[randomGenerated]
-
我已经尝试过了,但是它一直返回 SolutionName.Person