将DataRow[]列的列结果添加到变量c#中



我想将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);

然后我创建一个名为resultDataRow[],它存储ID=1:的行

DataRow[] result = table.Select("ID = 1");

我想要实现的最后一步是将BugDescription值添加到名为description的字符串中。

我将如何实现这一点?

您的代码

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();

我知道我很晚才给出答案,但是,我们可以在答案列表中再添加一个。

由于datatable.select以数组的形式向我们提供结果,因此我们要知道,我们正在为每一行数组中的列获取itemarray。用下面的例子来简化这个语句。

如果我们知道/记住/使用列位置/编号而不是列名,我们可以使用"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

假设行>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[0]是第一行&ItemArray[0]是的第一列

如果您有一个DataRows数组,因为您声明它为

DataRow[]

您可以访问它作为:

string resultBug = result[0]["BugDescription"];

但是,由于您只期望一行(并且您要判断是否总是期望返回一行),因此您应该将其声明为纯DataRow:

DataRow result = table.Select("ID = 1")[0];
string resultBug = result["BugDescription"].Dump();

Select返回一个行数组,因此应使用[0]对其进行索引以获取第一个匹配项。

如果你知道你只会得到一行,你可以把整个事情浓缩到这个

string description = table.Select("ID = 1").First().Field<string>("BugDescription");

要实现目标,您需要这样的东西:

if (result.Length > 0)
{
    var description = result[0]["BugDescription"].ToString();
}

最新更新