简体   繁体   中英

Getting Count Of Rows In DataTable With Variable

I am wanting to get a count of rows in my DataTable that meet specific criteria. My issue (I think) is that I am trying to use a column name as part of the Select statement. So this is what I have:

string twodigmonth = DateTime.Now.ToString("MM");
DataRow[] Test= dataTable1.Select(" " + dateasstring.Split('/')[0] + " = " + "'" + twodigmonth + "'");

I get a compile error of:

The name dateasstring does not exist in the current context.

But I have a column in my datatable that is string data type named this.

DataTable dataTable1 = new DataTable();
dataTable1.Columns.Add("dateasstring", typeof(string));

Instead of fiddling around with the odd and old DataTable.Select syntax, why don't you use the modern and much more powerful LINQ?

int currentMonth = DateTime.Today.Month;
int matchingRows = dataTable1.AsEnumerable()
 .Count(r => DateTime.Parse(r.Field<string>("dateasstring")).Month == currentMonth);

I would store the dateasstring as real DateTime , then you don't need to parse it every time.

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