在 C# 中,我对返回字符串中的列表有疑问

In C# i have a issue with List from returned string

我从数据库中收到一个包含此内容的字符串

One;Two;Three

我想将这些值存储在 reportTypeCodes 属性 中 class.

public class ReportTypeCode
{
    public string codeValue { get; set; }
}

public class Root
{
    public string name { get; set; }
    public DateTime creationDateTime { get; set; }
    public List<ReportTypeCode> reportTypeCodes { get; set; }
}

这是我目前的尝试:

Var Obj = new Root(){
           name="Test",
           creationDateTime=Convert.ToDateTime("2021-11-08),
           reportTypeCodes=?? // Don't know how to assign it.
    }

我该怎么做?

可以这样写:

var Obj = new Root()
{
    name = "Test",
    creationDateTime = Convert.ToDateTime("2021-11-08"),    
   reportTypeCodes = new List<ReportTypeCode>(){
        new ReportTypeCode(){ codeValue = "one"},
        new ReportTypeCode(){ codeValue = "two" }
   }
};

有点取决于你想做什么...

        var rootTest = new Root();

        rootTest.reportTypeCodes = new List<ReportTypeCode>()
        {
            new ReportTypeCode()
            {
                codeValue = "hello world"
            },
            new ReportTypeCode()
            {
                codeValue = "hello world 2"
            },
        };

        foreach(var code in rootTest.reportTypeCodes)
        {
            Console.WriteLine(code.codeValue);
        }

我想你正在寻找这个:

Var Obj = new root(){
           name="Test",
           creationDateTime=Convert.ToDateTime("2021-11-08),
           reportTypeCodes= new List<ReportTypeCode>{
               new ReportTypeCode { codeValue = "A"; },
               new ReportTypeCode { codeValue = "B"; }
           }
    }

System.Linq的帮助下,你可以很容易地做到这一点,见下文^^

using System.Linq;


new Root()
{
     name="Test",
     creationDateTime=Convert.ToDateTime("2021-11-08"),
     reportTypeCodes= "One;Two;Three"
           .Split(';')
           .Select(x => new ReportTypeCode(){codeValue = x})
           .ToList()
}

首先,您要获取字符串并将其拆分为每个 ';' 字符。为此,请使用 Value.Split(';').
然后你想把每个部分都变成一个ReportTypeCode。为此,您可以像这样使用 LINQ 方法 Select.Select(s => new ReportTypeCode { codeValue = s }).
最后,你想得到一个列表,所以你需要调用.ToList()(这是另一个LINQ方法)。
全部放在一起:

Value.Split(';').Select(s => new ReportTypeCode { codeValue = s }).ToList()