简体   繁体   中英

Convert IEnumerable<dynamic> to string[]

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"
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM