Convert IEnumerable<dynamic> to string[]

2.7k Views Asked by At

I have the code below, basically returns a single column of string values from a DB using MassiveORM.

The Query() method returns IEnumerable. I'm trying to find out how to cast or convert that to a simple string array.

Using the below I get

Unable to cast object of type 'System.Object[]' to type 'System.String[]

Thanks

var response = new MakesResponse();
var tbl = new DynamicModel("SONICAPI");
string sql = "EXEC pGetMakes";
var result = tbl.Query(sql);

return new MakesResponse()
{
makes = (string[])result.ToArray(),
ExecutionTime = sw.ElapsedMilliseconds,
Result = "200",
ResultText = "OK",
Source = "DB"
};
1

There are 1 best solutions below

8
Patrick Hofman On

You can cast the enumerable items. This will only work if they are really string:

makes = result.Cast<string>().ToArray()

Else, you can call ToString, if there is a good implementation of it:

makes = result.Select(o => o.ToString()).ToArray()