如何制作包含列表的类的列表

本文关键字:列表 包含 何制作 | 更新日期: 2023-09-27 18:32:52

我有一个类 Person 用于向 Person 添加一些数据。从第二个类ListOfP,我能够在每个添加新人后显示数据。现在我需要一些帮助来将每个新人放入列表中,并能够显示列表中的每个人及其所有详细信息。任何帮助将不胜感激。

class Person
{
    public List<string> PhoneNbrList = new List<string>();
    public List<string> GetListOfListOfP() { return PhoneNbrList; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void AddNewPerson()
    {
        PhoneNbrList = new List<string>();
        int i = 1;
        string str = "";
        bool stop = false;
        do
        {
            Console.Write("PhoneNbr [" + i + "]: ");
            str = Console.ReadLine();
            if (str == "n")
                stop = true;
            else
                PhoneNbrList.Add(str);
            i++;
        } while (!stop);
        Console.Write("First name: ");
        FirstName = Console.ReadLine();
        Console.Write("Last name: ");
        LastName = Console.ReadLine();
    }
    public void ShowPersonData() 
    {
        for (int i = 0; i < PhoneNbrList.Count; i++)
            Console.WriteLine("PhoneNbr[" + (i + 1) + "]: " + PhoneNbrList[i]);
        Console.WriteLine("First name: " + FirstName);
        Console.WriteLine("Last name: " + LastName);
    }
}

This is the second class
class ListOfP
    {
        static List<Person> ListP = new List<Person>();
        static void Main(string[] args)
        {
            Person lp = new Person();
            int counter = 1;
            lp.AddNewPerson();
            lp.ShowPersonData();
            ListP.Add(lp);

            lp.AddNewPerson();
            lp.ShowPersonData();
            ListP.Add(lp);
            Console.ReadLine();
        }
}

如何制作包含列表的类的列表

获取你的人类;

class Person
{
    public List<string> PhoneNbrList = new List<string>();
    public List<string> GetListOfListOfP() { return PhoneNbrList; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
} 

然后在需要人员列表的地方使用泛型;

List<Person> myList = new List<Person>;
Person x = new Person();
myList.Add(x);

然后,您可以遍历此列表 - 或者对它做任何您想做的事情

foreach (Person p in myList)
{
//Do something
}

据我了解,你需要这样的东西:

更新:

class Person
{
    public Person()
    {
      PhoneNbrList = new List<string>();
    }
    public List<string> PhoneNbrList;
    public List<string> GetListOfListOfP() { return PhoneNbrList; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
List<Person> objPerson = new List<Person>();
Person obj1 = new Person();
//Initialise obj1 here
objPerson.Add(obj1);
Person obj2 = new Person();
//Initialise obj2 here
objPerson.Add(obj2);
......// Add all the objects to list in same manner

// Query through list
foreach(var item in objPerson)
{
   // Access each of the items of list here
   foreach(var phoneNumbers in item.PhoneNbrList)
   {
      **//Access your each phone number here**
   }
}