Wolfish
Wolfish

Reputation: 970

Targeting a specific column in a DataRow

I'm trying to perform the C# equivalent of Select * where [columnname] = [value]. I began with a foreach loop to iterate through the table row by row, however I had forgotten that one cannot access a column via row.column["<colname>"].

How do I achieve this objective? Most of the examples I have seen target one specific row with the intention of casting it's value to a string, however my task is to move all entries with a value of DateTime == < DateTime.Today to an archived table.

Can I continue with the following code? Or am I approaching this in the wrong manner?

void archiveDates()
{
   foreach (DataRow row in workingupdates.storageTable.Rows)
   {
       //target DateTime column here                         
   }
}

Upvotes: 0

Views: 136

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460268

You can use the Field extension method that is strongly typed and also supports nullable types. You have an overload for the index, name or the DataColumn(among others):

foreach (DataRow row in workingupdates.storageTable.Rows)
{
   DateTime dt = row.Field<DateTime>("columnname");          
}

If you instead want to find all rows where the date column has a specific value you can use Linq-To-DataTable:

var matchingDataRows = workingupdates.storageTable.AsEnumerable()
    .Where(row => row.Field<DateTime>("columnname") == dateTimeVariable);

Now you can simply enumerate this query:

foreach (DataRow row in matchingDataRows)
{
   // ...                      
}

Or create a collection like

  • a DataRow[] with matchingDataRows.ToArray() or
  • a List<DataRow> with matchingDataRows.ToList()
  • a new DataTable with matchingDataRows.CopyToDataTable()

Note that you have to add System.Linq; to the top of the file.

Upvotes: 3

Related Questions