I'd like to get a list of strings from an Excel range where the data could be mixed types (strings, doubles, etc.). I tried using this:
List<string> rangeToList(Excel.Range inputRng)
{
object[,] cellValues = (object[,])inputRng.Value2;
List<string> lst = cellValues.Cast<string>().ToList();
return lst;
}
But the line with Cast<string>
returns this error:
Unable to cast object of type 'System.Double' to type 'System.String'
How can I convert this array of objects into my desired list?
First you should cast to object
to make list of object and after that you should use ConvertAll
(msdn) to convert object
to string
.
List<string> rangeToList(Microsoft.Office.Interop.Excel.Range inputRng)
{
object[,] cellValues = (object[,])inputRng.Value2;
List<string> lst = cellValues.Cast<object>().ToList().ConvertAll(x=> Convert.ToString(x));
return lst;
}
Cast
won't implicitly convert a number to a string, but you can call ToString
on each object:
List<string> lst = cellValues.Cast<object>()
.Select(o => o.ToString())
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With