如何将多个值添加到列表C#

时间:2016-07-27 00:25:13

标签: c#

我在列表中添加值时,我有以下代码。

var NoLiftingList = new List<SQLFields>();

SQLFields nolifting = new SQLFields();
nolifting.Field1 = "No lifting";
NoLiftingList.Add(nolifting);

SQLFields extremelifting = new SQLFields();
extremelifting.Field1 = "Up to 100 lbs (extreme lifting)";
NoLiftingList.Add(extremelifting);

我该如何简化?而不是一直初始化新对象。

这是下面更新的全班的代码。

由于

3 个答案:

答案 0 :(得分:2)

您可以使用此内联构造函数语法(工作示例)添加到列表,并在类上设置属性:

using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var NoLiftingList = new List<SQLFields>
        {
            new SQLFields
            {
                Field1 = "No Lifting"
            },
            new SQLFields
            {
                Field1 = "Up to 100lbs (extreme lifting)"
            }           
        };
    }
}

public class SQLFields
{
    public string Field1 { get; set; }
}

答案 1 :(得分:1)

试试这个

var NoLiftingList = new List<SQLFields>()
{
    new SQLFields()
    {
        Field1 = "No lifting"
    },
    new SQLFields()
    {
        Field1 = "Up to 100 lbs (extreme lifting)"
    }
};

答案 2 :(得分:1)

使用具有匿名类型的对象初始化器

var NoLiftingList = new List<SQLFields>(){ 
               new SQLFields() { Field1 = "No lifting"}, 
               new SQLFields() { Field1 = "Up to 100 lbs (extreme lifting)"}
};

参考:MSDN Link