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

本文关键字:列表 添加 | 更新日期: 2023-09-27 17:58:52

嗨,当我向列表中添加值时,我有以下代码。

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

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

这是下面更新的整个类的代码。

感谢

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

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

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

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

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

参考:MSDN Link

试试这个

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