I am receiving from the database a single string with this content
One;Two;Three
and I want to store those values in the reportTypeCodes
property in the following 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; }
}
This is my current attempt:
Var Obj = new Root(){
name="Test",
creationDateTime=Convert.ToDateTime("2021-11-08),
reportTypeCodes=?? // Don't know how to assign it.
}
How can I do it?
CodePudding user response:
First you want to take your string and split it on every ';'
character. To do this, use Value.Split(';')
.
Then you want to take each section and turn it into a ReportTypeCode
. To do this, you can use the LINQ method Select
like so: .Select(s => new ReportTypeCode { codeValue = s })
.
Finally, you want to get a list, so you need to call .ToList()
(it is another LINQ method).
All put together:
Value.Split(';').Select(s => new ReportTypeCode { codeValue = s }).ToList()
CodePudding user response:
With the help of System.Linq
you can do it quite easy, see below^^
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()
}
CodePudding user response:
You can write it in the following way:
var Obj = new Root()
{
name = "Test",
creationDateTime = Convert.ToDateTime("2021-11-08"),
reportTypeCodes = new List<ReportTypeCode>(){
new ReportTypeCode(){ codeValue = "one"},
new ReportTypeCode(){ codeValue = "two" }
}
};
CodePudding user response:
Depends a bit on what you want to do...
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);
}
CodePudding user response:
I think you're looking for this:
Var Obj = new root(){
name="Test",
creationDateTime=Convert.ToDateTime("2021-11-08),
reportTypeCodes= new List<ReportTypeCode>{
new ReportTypeCode { codeValue = "A"; },
new ReportTypeCode { codeValue = "B"; }
}
}