首页 > 解决方案 > 使用实际上是列表的类对象数组

问题描述

我需要弄清楚如何声明一个数组,并且数组中的每个对象都是另一个对象的列表。

所以结构会是这样的:

myArray[0] = List<MyObject>();
myArray[1] = List<MyObject>();

MyObject 有 3 个部分:

int anId;
string firstName;
string LastName;

我该如何声明并正确初始化它?我对其他想法持开放态度。

标签: c#arrays.netlist.net-core

解决方案


你可以这样做:

var items = new List<MyObject>[4];
items[0] = new List<MyObject>();
items[1] = new List<MyObject>();
items[2] = new List<MyObject>();
items[3] = new List<MyObject>();

或这个:

List<MyObject>[] items = {
    new List<MyObject>(),
    new List<MyObject>(),
    new List<MyObject>(),
    new List<MyObject>()
};

但我想知道你是否真的想要这个:

var items = new List<List<MyObject>>();
items.Add(new List<MyObject>);
items.Add(new List<MyObject>);
items.Add(new List<MyObject>);
items.Add(new List<MyObject>);

推荐阅读