Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to custom object list c#

I have a array:-

private string[][] barValues = new string[][] { new string[]{ "1.9", "5.8", "4.8", "Since Inception", "24-Jan 2014 to 24 Jun 2014" },
                                                new string[]{"1.2", "16.5","9.8", "Year to date","01-Apr 2014 to 24-Jun 2014" }, 
                                                new string[]{"11.6","28.8","23.5","Last quarter","01-Jan to 24-Jun 2014"} };

I want to convert this array into my custom list :-

List<Portfolio> list = new List<Portfolio>();

I tried doing :-

List<Portfolio> list=myArray.Cast<Portfolio>().ToList();

But I get a error:-

System.InvalidCastException: Cannot cast from source type to destination type.

How do I do this conversion?

like image 644
user3146095 Avatar asked Mar 18 '23 21:03

user3146095


1 Answers

You will need to use the Select operator and assign your array of strings to your Portfolio object. Something like this:

myArray.Select(array => new Portfolio { Field1 = array[0], Field2 = array[1] }).ToList()
like image 198
LazyOfT Avatar answered Mar 29 '23 07:03

LazyOfT