0

I have numeric data in a text file with column headers. I found a great solution for reading string data into a datatable here

Reading Comma Delimited Text File to C# DataTable, columns get truncated to 255 characters

I tried to adapt it for numeric data with no success. After I converted the string array to a double array I tried to add a row like this

myDatatable.Rows.Add(myDoubleArray)

which foes not seem to give me anything. I didi try to convert the double to objects and stick numbers in as in the code below:

var objectNumbers = rowData.Cast<object>().ToList();
data.Rows.Add();
for (var j = 0; j < columns.Length; j++)
{
    data.Rows[data.Rows.Count - 1][j] = objectNumbers[j];
}

Then I ended up with the numbers as strings.

Community
  • 1
  • 1
spainchaud
  • 365
  • 3
  • 12

1 Answers1

0

Somehow my question got messed up. Probably due to a failure at multitasking. So this is an update to my question.

I can now get the datatable to hold doubles, if I add columns and rows as follows:

myDataTable.Columns.Add(columnName, typeof(double));
var dataAsStrings = line.Split(charDelimiters, StringSplitOptions.RemoveEmptyEntries);

// convert to doubles
var dataAsDouble = new double[dataAsStrings.Length];
for (var i = 0; i < dataAsStrings.Length; i++)
{
    var isConverted = Double.TryParse(dataAsStrings[i], out dataAsDouble[i]);
    if (!isConverted) rowData[i] = Double.NaN;
}

var objectNumbers = dataAsDouble.Cast<object>().ToList();
myDataTable.Rows.Add();

for (var j = 0; j < columns.Length; j++)
{
    myDataTable.Rows[myDataTable.Rows.Count - 1][j] = objectNumbers[j];
}

Part of the key for me was adding columns as typeof(double). I got nothing to work until I did that. I was just lucky to find that suggestion on these forums. As you can see this code is all rather messy, but simpler attemps did not work for me. Can someone show me a simpler method method to get these results? Maybe something using Linq?

spainchaud
  • 365
  • 3
  • 12