Janty
Janty

Reputation: 1714

Cast DataRow [] to string array fires exception "Unable to cast object of type 'System.Int32' to type 'System.String'."

I need a string array of the first column of the DataRow [] drs. I tried below one line code but it is not working.

The datatype in the DataTable is Int, I need to connvert it to string array.

Am I missing some? Please suggest me.

DataRow[] drs = ds.Tables[1].Select();

Sorry I need one column value to string array.

 string[] drsArray = drs
                .AsEnumerable()
         .Select(row => row.Field<string>("role_id")) //Here getting the exception

I have tried the @Daniel's logic with ,Its working now. Now Is there possible to reduce some line of code Please.

 string[] drsArray = (drs
                        .AsEnumerable()
                 .Select(row => row.Field<int>("role_id"))
                 .Select(i => i.ToString()).ToArray());

Upvotes: 0

Views: 1241

Answers (2)

Steve
Steve

Reputation: 216293

An old fashioned way should be enough in your case. (At least, in my opinion, it is more readable)

List<string> firstCol = new List<string>()
foreach(DataRow row in drs)
    firstCol.Add(row[0].ToString());

Of course a List could be seen as an array without to much problems

foreach(string s in firstCol)
    Console.WriteLine(s));

Upvotes: 1

Daniel Mann
Daniel Mann

Reputation: 59020

Call ToString on it instead:

drs[0].ItemArray.Select(i => i.ToString()).ToArray();

Upvotes: 5

Related Questions