0

I have written a program wherein I fetch a data from an API and the built in API Parser stores the data retrieved in Multi-dimensional array format. I am converting the Multi-dimensional array into DataTable using the codes below:

for (i = mdArray.GetLowerBound(0); i <= mdArray.GetUpperBound(0); ++i)
{
    DataRow myRow = null;
    myRow = dtResults.NewRow();
    for (j = mdArray.GetLowerBound(1); j <= mdArray.GetUpperBound(1); ++j)
    {

        myRow[Convert.ToInt32(j)] = mdArray[i, j];      
    }
    dtResults.Rows.Add(myRow);
}

mdArray is the multi dimentional array i am referring to.

The above codes works fine when the size or length of the array is less than 100. However, for bigger sizes, like >5000 elements, it takes me too much time to insert the data from array to the DataTable I am building on the fly since i am looping for each element.

Is there a way wherein we can convert Multi Dimentional Array directly to DataTable without doing looping to each element to maximize the performance?

Appreciate your help.

Thank you.

Ian Siñel
  • 95
  • 1
  • 11
  • 2
    hello, did you think of using LINQ ? refer to https://stackoverflow.com/a/8932997/3963522 – AhmadMM Mar 20 '19 at 08:36
  • @AhmadMM will using LINQ improve the performance? I would have thought underneath the LINQ statement it would be doing a loop internally anyway? – IanSoc Mar 20 '19 at 10:11
  • In my opinion, try to change your way of parsing data into 2D-array , instead of 2D-array use a LIST if your 2D array contains only integers or List it'll be much easier to parse it to datatable and you can use LINQ, in addition, the operation will be fast, and efficient – AhmadMM Mar 20 '19 at 10:24
  • @AhmadMM The 2D Array is the returned value of the External API package I'm using. Thank you. – Ian Siñel Mar 20 '19 at 10:49
  • @IanSiñel - Can you have your API return a `T[][]` rather than `T[,]`? – Enigmativity Mar 20 '19 at 11:48
  • Hi @Enigmativity Unfortunately, not. That is an external API which I don't have control of. I am currently doing a workaround which I dump the array into excel file. By dumping it in excel, I don't have to loop over each element as I can have MyExcel.Range[rngAddress].Value = MultiDimensional array. Then after this, I will have to perform SQL select over the excel file and have the SQL results to DataTable object. I am not sure if this is the most efficient way though. – Ian Siñel Mar 20 '19 at 13:41
  • @IanSiñel - Then try having a play with `.OfType()` and see if you can do this with a single enumerable. – Enigmativity Mar 20 '19 at 22:05

0 Answers0