如何填充类中的列表

时间:2013-09-05 15:11:19

标签: c# list

我有一个简单的类,它有一些属性,一个属性是列表。

public IList<CounterReclaimCardModels> CounterReclaimCards { get; set; }
public long AggID { get; set; }
public string id { get; set; }

我实例化了该类并向其中添加了一些数据,但我无法弄清楚如何将数据添加到列表中。下面是我如何实例化类

以下是我如何实例化列表并尝试添加它

 CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>()
        {
            CounterReclaimID = 1,
            ReclaimType = "Rule22Pool",
            ReclaimDisposition = "None",

        };

4 个答案:

答案 0 :(得分:3)

这会将CounterReclaimCardModels类型的单个项目放入新列表中:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>
    {
        new CounterReclaimCardModels
        {
            CounterReclaimID = 1,
            ReclaimType = "Rule22Pool",
            ReclaimDisposition = "None",
        }
    };

答案 1 :(得分:2)

像这样:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>()
{
    new CounterReclaimCardModels()
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    }

};

答案 2 :(得分:2)

创建列表时,您可以使用如下的起始值加载它:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>
{
    new CounterReclaimCardModels()
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    },
    new CounterReclaimCardModels()
    {
        CounterReclaimID = 2,
        ReclaimType = "AwesomeThing",
        ReclaimDisposition = "None"
    },
    variableForAnExistingCounterReclaimCardModels,
    //etc...
};

或者,您可以使用Add方法:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>();
CounterReclaim.CounterReclaimCards.Add(new CounterReclaimCardModels()
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    });

CounterReclaim.CounterReclaimCards.Add(new CounterReclaimCardModels()
    {
        CounterReclaimID = 2,
        ReclaimType = "AwesomeThing",
        ReclaimDisposition = "None"
    });

CounterReclaim.CounterReclaimCards.Add(variableForAnExistingCounterReclaimCardModels);

此外,您可以使用一些值初始化列表,然后使用“添加”稍后添加更多内容。

答案 3 :(得分:1)

您必须在列表中创建每个项目的实例:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>()
{
    new CounterReclaimCardModels
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    }
    // ...
};