Associations类(列表中的列表)

本文关键字:列表 Associations | 更新日期: 2023-09-27 18:09:32

我有两个相互关联的类,一个镇有很多人。

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的实例和与之关联的记录之后,我想在Form中显示结果。

    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 ..)向人们展示1、2、3等)?

Associations类(列表中的列表)

必须将列表作为属性公开

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

然后引用它:

var people = myTown.CollectionOfPeople;

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

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

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

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