使用where子句过滤数据表行

时间:2013-07-08 19:46:23

标签: c# datatable dataset where-clause datarow

我有一个DataTable,我从DataSet中提取。从DataTable,我想使用Where子句返回特定的行。我查看了“How can I select a row from a datatable using two variable values?”,但收到了错误

  

“无法将类型'System.Data.DataRow []'隐式转换为   'System.Data.DataRow'“

我搜索了谷歌,但找不到解决方案。

我的代码是:

mySqlDataAdapter.Fill(myDataSet);

DataTable dtTable = myDataSet.Tables[0];
DataRow dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString());

我该如何解决这个问题?

6 个答案:

答案 0 :(得分:14)

即使您的查询只选择一行,DataTable的Select方法也会返回DataRow数组

DataRow[] dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString());

然后,如果你真的只想要一行,你可以轻松地获取预期行检查数组的长度。在这种情况下,我认为真的不需要花哨的Enumerable扩展方法

if(dr.Length > 0)
{
    string avalue = dr[0]["AColumnName"].ToString();
    ...
}

答案 1 :(得分:1)

Select()返回一个行数组,然后将其分配给一行。

你可以这样做:

DataRow dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()).First();

var dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString());

将为您提供一系列行。

答案 2 :(得分:0)

假设只有一个独特的结果

DataTable dtTable = myDataSet.Tables[0];
DataRow[] drs = dtTable.Select("VendorID = " + Session["VendorId"].ToString());
if(drs.Length > 0)
    DataRow dr = drs[0];

答案 3 :(得分:0)

DataTable.Select()会返回DataRow数组。

DataRow[] dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString());

如果您只想要第一条记录,

DataRow[] dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()).FirstOrDefault();

答案 4 :(得分:0)

使用方法First()

DataRow dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()).First();

答案 5 :(得分:0)

在您的情况下,Select()方法返回一个内部有一个DataRow的IEnumerable集合。您必须使用FirstOrDefault()从该集合中提取DataRow。

相关问题