我希望将DataRow[]
的值返回到c#中的字符串
这是我的DataTable
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("BugDescription", typeof(string));
table.Columns.Add("UnitPrice", typeof(double));
table.Rows.Add(1, "Bug 1", 10.00);
table.Rows.Add(2, "Bug 2", 20.00);
然后创建一个名为DataRow[]
的result
,它存储ID =1的行:
DataRow[] result = table.Select("ID = 1");
我要完成的最后一步是将BugDescription值添加到名为description
的字符串中。
我怎样才能做到这一点?
发布于 2013-08-07 06:31:33
你的代码
DataRow[] result = table.Select("ID = 1");
告诉您您有一个DataRows数组。这意味着你在这里可能有不止一张唱片。所以,现在要看你要分配哪一行了。如果你认为这是第一次,你可以这样做。
if(result.Length > 0)
{
string description = Convert.ToString(result[0]["BugDescription"]);
}
用linq的方式
string description = table.Rows.OfType<DataRow>().Where(row => (string)row["ID"] == "1").Select(row => (string)row["BugDescription"]).First();
发布于 2018-06-30 08:59:03
我知道我给出答案的时间已经很晚了,但是,我们可以在答案列表中再加一个。
当datatable.select以数组的形式给出结果时,我们要知道的是,我们正在为每一行数组中的列获取项目数组。用下面的例子简化这个语句。
如果我们知道/记住/使用列位置/编号而不是列名,我们可以使用"ItemArray“
//ID Name Age
//100 Name 100 Age 100
//101 Name 101 Age 101
//102 Name 102 Age 102
假设是单排。
DataTable dt=new DataTable();
//Assigning some data into dt. with columns ID, Name, Age.
DataRow[] dr=dt.Select("ID=100");
string PersonID=dr[0].ItemArray[0].Tostring().trim(); //first column is ID
string PersonName=dr[0].ItemArray[1].Tostring().trim(); //second column is Name
string PersonAge=dr[0].ItemArray[2].Tostring().trim(); //third column is Age
因此,变量将具有以下详细信息。
// PersonID= 100; PersonName= Name 100; PersonAge= Age 100
假设rows>1 (本例中为2)
dr=dt.Select("ID>100");
string PersonID_1=dr[0].ItemArray[0].Tostring().trim(); //first column is ID
string PersonName_1=dr[0].ItemArray[1].Tostring().trim(); //second column is Name
string PersonAge_1=dr[0].ItemArray[2].Tostring().trim(); //third column is Age
string PersonID_2=dr[1].ItemArray[0].Tostring().trim(); //first column is ID
string PersonName_2=dr[1].ItemArray[1].Tostring().trim(); //second column is Name
string PersonAge_2=dr[1].ItemArray[2].Tostring().trim(); //third column is Age
因此,变量将具有以下详细信息。
// PersonID_1= 101; PersonName_1= Name 101; PersonAge_1= Age 101
// PersonID_2= 102; PersonName_2= Name 102; PersonAge_2= Age 102
要记住:第一行或列索引id总是以0开头。因此,dr是第一行,ItemArray是第一列。
发布于 2013-08-07 06:24:30
如果您有一个DataRows数组,就像声明它之后一样
DataRow[]
您可以通过以下方式访问它:
string resultBug = result[0]["BugDescription"];
但是,由于您只期望一行(并且要判断是否总是期望返回一行),所以应该将其声明为普通的DataRow:
DataRow result = table.Select("ID = 1")[0];
string resultBug = result["BugDescription"].Dump();
Select将返回一个行数组,因此您应该对其进行索引,以获得第一次出现。
https://stackoverflow.com/questions/18105858
复制相似问题