簡體   English   中英

將不同類型的數據保存在C#的列表中

[英]Save different types of data in a List in C#

我有一些數據,例如姓名,ID,年齡,地址,電話。 每次用戶輸入數據時,它將保存到List<> 我為每個數據使用List<> 還有其他選擇,我只能使用一個List<> 哪個可以保存所有數據?

這是我的代碼。

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

我還想到了使用列表框打印數據。 我的另一種選擇是僅在一個列表框中打印出所有數據。

絕對,聲明一個像這樣的類...

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

為什么不使用這些字段創建對象(類)。 然后,您可以僅創建“用戶”對象的數組。

每當傳遞數據時,只需創建對象的新實例,然后將其添加到數組中即可。

您可以使用人員對象,設置人員的屬性並將人員添加到列表中

List<Person>

創建是使用List<YourClass>的最佳解決方案。

如果您不想為它創建一個類,則可以將其與最新版本的C#一起使用。 使用元組。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM