简体   繁体   中英

Get Specific Column From DataTable After Date Filter

I have a data table with 10 columns and I want to filter on only two columns. One column is the file date and I have logic that gets values of the file date in the last month. This functions properly, except that I can't get the other column which is the meter reading. The mental logic is below:

(1) Get column name File Date, (2) get column name Meter Reading, and (3) if the column File Date is between now and last month, do stuff with the meter reading values (not File Date values, as this is only a filter).

foreach (DataRow r in datatable.Rows)
{
  foreach (DataColumn c in datatable.Columns)
  {
    if (c.ColumnName == "File Date")
    {
      // filter date logic works, but now can't access the meter reading
    }

I tried the inverse, looping first through the columns (and then later would loop through the rows), yet the logic of c.ColumnName[0] for instance, doesn't get the first value in the columns, but rather the first letter of all columns. I also tried c.ColumnName("File Date") and c.Column("Meter Reading"), which is invalid logic.

I also thought I could declare a variable within the columns loop, which would get the columns that I want. DataColumn meterread = col.ColumnName("Meter Reading"), except this doesn't return it either. I looked to see if there was a way to filter using lamba where I would filter the column to a specific name of "Meter Reading" or "File Date".

Got it: filedate = row["File Date"]; meterreading = row["Meter Reading"] filedate = row["File Date"]; meterreading = row["Meter Reading"]

you can filter datatable rows as DataView dv = new DataView(yourDatatable); dv.RowFilter = "query"; // query example = "Name = someName" DataView dv = new DataView(yourDatatable); dv.RowFilter = "query"; // query example = "Name = someName"

once you have the table with all the relevant rows, apply ur logic to any column.

Alternatively, you dont need to loop through columns. you can simply do r["File Date"] to get the value of FileDate for that particular row. if value satisfy your filter, you can access r["MeterReading"].

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