关联类(列表中的列表)

时间:2013-04-15 18:19:05

标签: c# forms list class

我有两个与一个和另一个相关的课程,一个城镇有很多人。

public class Town
{
    List<People> collectionOfPeople;

    public string town { get; set; }

    public Town()
    {
        townName = "";

        collectionOfPeople = new List<People>();
        collectionOfPeople.Add(new People());
    }

    public Town(string tmp_townName)
    {
        townName = tmp_townName;

        collectionOfPeople = new List<People>();
        collectionOfPeople.Add(new People("Daniel Smith", "22"));
    }
}

在List中构建Town的实例,以及与之关联的记录之后,我想在表单上显示结果。

    private int numberOfPeople;
    private int currentPeopleShown;
    private int numberOfTown;
    private int currentTown;
    private List<People> peopleList;
    private List<Town> townList;

    // ************************* Methods/Functionality
    private void LoadData()
    {
        txt_townName.Text = (townList[0]).townName;
        txt_peopleName.Text = (peopleList[currentPeopleShown]).name;

        numberOfPeople = peopleList.Count();
        currentPeopleShown = 0;
    }

如何引用List中的List,显示或计算其中的记录数(town0 ..显示people1,2,3等)?

3 个答案:

答案 0 :(得分:1)

您必须将列表公开为属性

public List<People> CollectionOfPeople { get; set; }
^                                      ^ ^    ^    ^

然后引用它:

var people = myTown.CollectionOfPeople;

答案 1 :(得分:0)

您可以使用SelectMany(...)将所有嵌套项合并为单个可枚举

townList.SelectMany(t=>t.collectionOfPeople).Count();

答案 2 :(得分:0)

  

如何在List中引用List,以显示或计算其中的记录数。 (town0 ..显示人员1,2,3等)

foreach (Town town in townList)
  foreach (People people in town.collectionOfPeople)
    MessageBox.Show(people.Name);