简体   繁体   中英

LINQ to Datatable - How to add an if condition in linq query where clause?

OleDbCommand commandSec = new OleDbCommand();
commandSec.CommandText = "SELECT [SectionName], [Strand], [ReqGrade], [GradeLevel] FROM tbl_section";
OleDbDataAdapter daSec = new OleDbDataAdapter(commandSec);
commandSec.Connection = conn;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
daSec.Fill(dt);
daSec.Fill(ds, "tbl_section");
var section = (from DataRow dr in dt.AsEnumerable()
    where (double)dr["ReqGrade"] >=  Convert.ToDouble(txt_genave.Text) &&
    (string)dr["GradeLevel"] == gradelevel
    select (string)dr["SectionName"]).FirstOrDefault();

I get an InvalidCastException: Specified cast it not valid.

I need to insert a class section to a particular student base on his/her GradeLevel and the ReqGrade.

I think your problem may be here:

from DataRow dr in dt.AsEnumerable()

Try:

from DataRow dr in dt.Rows.AsEnumerable()

The DataTable itself is not enumerable, but the rows within it are.

I was able to reproduce your issue and avoid the error by changing

where (double)dr["ReqGrade"] >= ...

to

where Convert.ToDouble(dr["ReqGrade"]) >= ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM