Convert Array to custom object list c#

user3146095 picture user3146095 · Aug 1, 2014 · Viewed 18.5k times · Source

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?

Answer

LazyOfT picture LazyOfT · Aug 1, 2014

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