我已经创建了一个数据在List
中的示例。这种定制类Person
仅仅是为了获取你原来上面的例子:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
这种方法随机化的名字在List<Person>
顺序:
public string GetRandomNames(List<Person> people)
{
int numberOfPeople = people.Count;
string nameLabel;
string[] names = new string[numberOfPeople];
Random r = new Random();
for(int i = 0; i<numberOfPeople; i++)
{
int randomIndex = r.Next(0, people.Count);
names[i] = people[randomIndex].Name;
people.RemoveAt(randomIndex);
}
foreach(string name in randomNames)
{
nameLabel += name + ", ";
}
return nameLabel;
}
对于这个例子的目的,我有创建列表如下。当然,您的列表将来自其他来源,例如您提到的SQL数据库。然后
List<Person> people = new List<Person>();
people.Add(new Person() { ID = 1, Name = "Nik" });
people.Add(new Person() { ID = 2, Name = "Steve" });
people.Add(new Person() { ID = 3, Name = "John" });
people.Add(new Person() { ID = 4, Name = "Denny" });
people.Add(new Person() { ID = 5, Name = "Joe" });
people.Add(new Person() { ID = 6, Name = "Mike" });
people.Add(new Person() { ID = 7, Name = "Elena" });
people.Add(new Person() { ID = 8, Name = "Michel" });
用法是沿着线的东西:
string nameLabel = GetRandomNames(people);
请让我知道这不回答你的问题。
很好的答案,除了打破一个基本的规则:避免使用Load事件处理程序,共同操作](http://stackoverflow.com/questions/4933958/vs2010-does-not-show-unhandled-exception-message-in-a-winforms-application-on-a) - 使用构造函数或显示()处理程序,而不是 – miroxlav
它不起作用,我得到错误:类型'列表(字符串)'的值不能转换为'字符串()'...:P – LazaBre
检查您的代码,您可能定义了'String()'而不是'列表(字符串)'。在我的代码中没有'String()',我使用'List(of String)' –