Home » excel » c# – Convert a generic array to a specific type

c# – Convert a generic array to a specific type

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using Interop to work with Excel in C#. I need two cells. This is how I get them:

cells = (Excel.Range)sheet.get_Range("V" + i, "W" + i);
System.Array values = (System.Array)cells.Cells.Value;

This returns the values I want, as tested with a foreach loop. But how do I get the elements into string variables? I tried this:

var stringValues = values.Cast<string>();

but I can’t access it in any way without raising an error.

How to&Answers:

A simple ConvertAll should suffice:

var stringValues = Array.ConvertAll(values, item => (string)item);

Answer:

the code var stringValues = values.Cast<string>(); is attempting to cast the array as a string. so, if you are trying to end up with an array of strings you can try:

var stringValues = new List<string>();

values.ToList().ForEach(cellValue=>stringValues.Add(cellValue.ToString());

this is off the top of my head, there is probably a terser way of expressing this

Answer:

You can try:

values.Select(o => o.ToString());