2012-06-28 73 views
1

我有几个数据,如姓名,身份证,年龄,地址,电话。每次用户输入数据时,它都会保存到List<>。我为每个数据使用List<>。有没有其他的选择,我只能使用一个List<>。哪些可以保存所有的数据?在C#中的列表中保存不同类型的数据#

这是我的代码。

List<String> list1 = new List<String>(); 
       list1.Add(name); 
List<String> list2 = new List<String>(); 
       list2.Add(ID); 
List<String> list3 = new List<String>(); 
       list3.Add(age); 
List<String> list4 = new List<String>(); 
       list4.Add(address); 
List<String> list5 = new List<String>(); 
       list5.Add(phone); 

for (int a = 0; a < list.Count; a++) // Loop through List with for 
{       
    listBox1.Items.Add(list1[i]); 
} 
for (int a = 0; a < list.Count; a++) // Loop through List with for 
{       
    listBox2.Items.Add(list2[i]); 
} 
for (int a = 0; a < list.Count; a++) // Loop through List with for 
{       
    listBox3.Items.Add(list3[i]); 
} 
for (int a = 0; a < list.Count; a++) // Loop through List with for 
{       
    listBox4.Items.Add(list4[i]); 
} 
for (int a = 0; a < list.Count; a++) // Loop through List with for 
{       
    listBox5.Items.Add(list5[i]); 
} 

我也想过使用listbox打印输出数据。我的另一种选择是只打印一个列表框中的每个数据。

回答

1

为什么不用这些字段创建一个对象(类)。 然后你可以创建一个“用户”对象的数组。

只要数据通过,您只需创建对象的新实例,然后将其添加到您的数组。

0

您可以使用一个人的对象,设置人的属性和人添加到列表中

List<Person> 
7

当然,声明这样的类...

public class Person 
{ 
    public Guid ID  { get; set; } 
    public string Name { get; set; } 
    public int Age  { get; set; } 
    public string Address { get; set; } 
    public string Phone { get; set; } 
} 

而且使用像这样..

List<Person> personList = new List<Person>(); 
personList.Add(new Person { Name = "Max", 
          ID  = Guid.NewGuid, 
          Address = "Unicorn Lane, Unicorn World", 
          Age  = 26, 
          Phone = "123456" }); 
+0

+1使用实质(人,personList),而不是像MyClass的毫无意义的术语。 +1使用对象初始化器语法。 – Val

+0

为什么感谢你那种先生:-) –

+0

然后我可以知道如何从列表中检索数据?即时通讯使用listBox1.Items.Add(personList [0]);并打印出“人” –

0

创建是在b您的问题的解决方案,使用List<YourClass>

0

如果你不喜欢为它创建一个类,还有另外一种选择,你可以使用最新版本的C#。使用一个Tuple。

var mylist = new List<Tuple<Guid,string,int,string, string>>(); 
myList.Add(new Tuple<Guid,string,int, string, string>(Guid.New(), "name", 18, "123 street", "1231231234")); 

之后,你可以访问它作为

var firstId = myList[0].Item1; 
var firstName = myList[0].Item2; 
相关问题