1

我有 2 个与一个和另一个相关联的类,一个城镇中有很多人。

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

在列表中构造一个城镇的实例以及与之关联的记录后,我想在表单上显示结果。

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

我将如何引用列表中的列表,以显示或计算其中的记录数(town0 .. show people1、2、3 等)?

4

3 回答 3

1

您必须将列表公开为属性

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

然后像这样引用它:

var people = myTown.CollectionOfPeople;
于 2013-04-15T18:22:11.817 回答
0

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

townList.SelectMany(t=>t.collectionOfPeople).Count();
于 2013-04-15T18:22:00.137 回答
0

我将如何引用列表中的列表,以显示或计算其中的记录数。(town0 .. 显示 people1,2,3 等)

foreach (Town town in townList)
  foreach (People people in town.collectionOfPeople)
    MessageBox.Show(people.Name);
于 2013-04-15T18:23:40.027 回答