Search code examples
c#excelexcel-dna

Converting Multi-Dimensional Array to Single, with nullable Values


I am using ExcelDNA/C#/Excel primarily. What I am essentially trying to do is convert a multi-dimensional array (namely a range of cells) to a singular dimensional array, using the following code:

private static string[] MultiToSingle(object[,] multiArray)
{
   List<string> tempList;
   string[] returnArray;
   tempList = new List<string>();

   //Add each element of the multi-dimensional Array to the list
   foreach (object oneObj in multiArray)
   {
      tempList.Add(oneObj.ToString());
   }
   //Convert the list to a single dimensional array
   returnArray = tempList.ToArray();
   return returnArray;
}

This works a treat, and is used a number of times throughout my project, however I would like to add some more functionality.

When I try to run this function with a range that contains an empty cell, it errors horribly, at the moment I just have a try/catch with an error message informing the user to enter N/A into any empty cells.

What I'd really like to do, is in this function perhaps, convert any 'null' or whatever Excel stores empty cells as to the text string "N/A".


Solution

  • Perhaps just:

    tempList.Add(oneObj == null ? "n/a" : oneObj.ToString());
    

    I can also think of ways to make it more efficient, if you want:

    string[] arr = new string[multiArray.Length];
    int i = 0;
    foreach (object oneObj in multiArray)
    {
        arr[i++] = oneObj == null ? "n/a" : oneObj.ToString();
    }
    return arr;
    

    This cuts out the intermediate list and a few backing array copies.