Filtering a datatable row using a where clause

2019-07-02 01:07发布

I have a DataTable that I am pulling from a DataSet. From the DataTable, I want to use the Where clause to return a particular row. I looked at "How can I select a row from a datatable using two variable values?" but I get an error

"Cannot implicitly convert type 'System.Data.DataRow[]' to 'System.Data.DataRow'"

I searched google, but could not find a solution.

My code is:

mySqlDataAdapter.Fill(myDataSet);

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

How can I resolve this?

6条回答
倾城 Initia
2楼-- · 2019-07-02 01:23

Asuming there is only one unique result

DataTable dtTable = myDataSet.Tables[0];
DataRow[] drs = dtTable.Select("VendorID = " + Session["VendorId"].ToString());
if(drs.Length > 0)
    DataRow dr = drs[0];
查看更多
在下西门庆
3楼-- · 2019-07-02 01:25

Select() is returning an array of rows, and you're assigning it to a single row.

You can do :

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

or

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

which will give you an array of rows.

查看更多
贼婆χ
4楼-- · 2019-07-02 01:31

Use the method First():

DataRow dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()).First();
查看更多
我只想做你的唯一
5楼-- · 2019-07-02 01:33

The Select() method returns an IEnumerable collection with one DataRow inside, in your case. You must extract the DataRow from that collection with FirstOrDefault() instead.

查看更多
三岁会撩人
6楼-- · 2019-07-02 01:42

DataTable.Select() returns an array of DataRow.

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

If you only want the first record,

DataRow[] dr = dtTable.Select("VendorID = " + Session["VendorId"].ToString()).FirstOrDefault();
查看更多
等我变得足够好
7楼-- · 2019-07-02 01:43

The Select method of a DataTable returns an array of DataRow even if your query selects only one row

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

Then, if you really expects just one row, you could easily grab the expected row checking for the length of the array. In this case it is my opinion that no fancy Enumerable extension methods are really needed

if(dr.Length > 0)
{
    string avalue = dr[0]["AColumnName"].ToString();
    ...
}
查看更多
登录 后发表回答