DataTable从字符串到特定列的int行 [英] DataTable from string to int row in specific column
问题描述
我正在从csv检索数据,该csv是用逗号分隔的文件,并且第一次将所有列表示为 string 类型.但是,当我将数据检索到 int 以便对其进行排序时,我想转换一个特定的列.
加载行时尝试了以下操作,
I am retriving data from a csv which is comma separated file and all the columns at the first time are represented as string type. But I want to convert a specific column, when I am retriving the data to int to be available to sort it.
I tried the following when I am loading the rows,
//rows loading
dr = dt.NewRow();
dr.ItemArray = sLine.Split(''|'');
if (dt.Columns.Contains(''ID''))
{ dt.Rows.Add(dr, typeof(int)); }
else
{ dt.Rows.Add(dr); }
但是没有用;当我尝试使用dataview对数据表进行排序时,仍然以 string ...
的形式获取它
也使用DataTable中的DataView进行了尝试,
But is not working; when I try to sort the datatable using a dataview is still getting it as a string...
Tried this too using a DataView from the DataTable,
DataView dv1 = new DataView(dt);
DataView dv2 = new DataView(dt);
int obj;
for ( int x= 0; x<dt.Rows.Count; x++)
{
int.TryParse(dv1[x][0].ToString(), out obj);
int.TryParse(dv2[x][0].ToString(), out obj);
}
dv1.Sort = "ItemNo ASC";
dv2.Sort = "ItemNo DESC";
但是如果我使用MeesageBox.Show(dv1 [0] [0] .ToString());数据以字符串形式给出,所以我得到了1,10,100等,而不是1,2,3 ...:confused:
but if I use MeesageBox.Show(dv1[0][0].ToString()); the data is in string is giving me, 1, 10, 100 an so on instead of 1, 2, 3 ...:confused:
推荐答案
当您拆分时排成字符串的行,即使它们中有数字,它们仍然只是字符串.
您需要在添加行之前定义架构,以确保数据类型正确( ^ ]).
定义架构可能还需要正确地转换数据(IIRC)的值.这意味着您应该使用 int.TryParse [
When you split the row into strings they are still just strings, even if there is a number in them.
You''ll want to define the schema before you add the rows to ensure the data types are correct (MSDN reference[^]).
Defining the schema may also require properly casting the values for your data (IIRC). This means you should likely use int.TryParse[^] to extract the value.
Cheers.
这篇关于DataTable从字符串到特定列的int行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!