如何列出一个列表中的列表?

时间:2014-12-02 13:51:37

标签: c#

我有一个类人员用于向一个人添加一些数据。从第二类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();
        }
}

2 个答案:

答案 0 :(得分:2)

让你的人上课;

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
}

答案 1 :(得分:0)

据我所知,你需要这样的东西:

<强>更新

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**
   }
}