我需要将数据表中的字符串解析为double。我有一个数据表(dt),它有不同的列,每个列都使用.ToString()
方法转换为字符串。但是,当我尝试输出数据的纬度和经度时,我收到错误“输入字符串格式不正确”。所以我想我的主要问题是,如何使用.ToString()
方法解析转换为字符串的对象中的文本..
using System;
using System.IO;
using System.Collections;
using System.Data;
namespace SalesMap
{
class SalesMap
{
private static DataTable InitData1()
{
//Datatable for entire list of zipcodes
DataTable datat = new DataTable("DATA");
DataColumn state = new DataColumn();
DataColumn county = new DataColumn();
DataColumn statecounty = new DataColumn();
DataColumn latitude = new DataColumn();
DataColumn longitude = new DataColumn();
DataColumn salesperson = new DataColumn();
//Add the columns to the datatable
datat.Columns.Add(state);
datat.Columns.Add(county);
datat.Columns.Add(statecounty);
datat.Columns.Add(latitude);
datat.Columns.Add(longitude);
datat.Columns.Add(salesperson);
return datat;
}
private static String InitPath()
{
string path = "C:/Documents and Settings/Andre/Desktop/salesmapdata/MapPointCountyLatLong.csv";
return path;
}
public static void Main()
{
try
{
DataTable dt = InitData1();
StreamReader sr = new StreamReader(InitPath());
String csvData = string.Empty;
while ((csvData = sr.ReadLine()) != null)
{
String[] data = csvData.Split(',');
//dt.Rows.Add(data);
DataRow newRow1 = dt.NewRow();
newRow1[0] = data[0].ToString(); //state
newRow1[1] = data[1].ToString(); //county
newRow1[2] = data[2].ToString(); //state|county
newRow1[3] = data[3].ToString(); //latitude
newRow1[4] = data[4].ToString(); //longitude
newRow1[5] = data[5].ToString(); //salesperson
dt.Rows.Add(newRow1);
Console.WriteLine("Row added for: dt");
}
foreach (DataRow row1 in dt.Rows)
{
double latitude1 = Double.Parse(row1[3].ToString());
double longitude1 = Double.Parse(row1[4].ToString());
if (row1[5].ToString() != "UNKNOWN" || row1[5].ToString() != "SALESMAN")
{
Console.WriteLine(latitude1);
Console.WriteLine(longitude1);
}
}
dt.WriteXml(@"c:\test\dt1.xml");
sr.Close();
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(@"c:\test\error.txt");
sw.WriteLine(e.Message.ToString());
sw.Close();
}
}
}
}
答案 0 :(得分:2)
首先,当从CSV文件中读取数据时,您不需要在每个数组元素上调用data[x].ToString()
,因为它们已经是字符串。
Double.Parse调用可能存在的几个潜在问题:
string.IsNullOrWhitespace()
或类似内容进行检查。Decimal.Parse()
接受文化作为参数(您可以提供CultureInfo.InvariantCulture
或任何其他CultureInfo
)。