cnd
cnd

Reputation: 33794

Selecting rows from DataTable by DateTime column (hours)

DatarowsForOneDay = dt.Select(
    dt.Columns[0].Caption + "='" + x.ToString("dd/MM/yyyy HH") + "'");

doesn't work, but

DatarowsForOneDay = dt.Select(
    dt.Columns[0].Caption + "='" + x.ToString("dd/MM/yyyy") + "'");

works.

So how can I select the date with a same hour?

Variable x type is DateTime.

Upvotes: 1

Views: 9704

Answers (4)

João Angelo
João Angelo

Reputation: 57728

The .Select method accepts a filter expression with the same syntax of the one used in DataColum.Expression. You can check MSDN entry for detailed information:

DataColumn.Expression Property

If LINQ is available you can do something like this:

DataTable dt = new DataTable();

dt.Columns.Add("DT", typeof(DateTime));

foreach (var item in Enumerable.Range(1, 20))
{
    dt.Rows.Add(new DateTime(2010, 3, 10, item, 20, 10));
}

DataRow[] rows = dt.Rows.Cast<DataRow>().Where(dr => 
    ((DateTime)dr["DT"]).ToString("yyyy-MM-dd HH") == "2010-03-10 10")
    .ToArray();

Console.WriteLine(rows.Length);

Upvotes: 2

Adeel
Adeel

Reputation: 19238

You can use this code. Iterate all rows in DataTable and add into searchRecords List according to same date and hour.

List<DataRow> searchRecords = new List<DataRow>();
string searchDateOnHour = DateTime.Now.ToString("dd/MM/yyyy HH");
foreach (DataRow item in table.Rows)
{
    DateTime recordDate;
    DateTime.TryParse(item["comDate"].ToString(), out recordDate);
    string recordDateHour = recordDate.ToString("dd/MM/yyyy HH");        
    if (searchDateOnHour == recordDateHour)
        searchRecords.Add(item);            
}

Upvotes: 2

garik
garik

Reputation: 5756

Use SUBSTRING or LIKE

or

dt.Columns[0].Caption + " LIKE '" + x.ToString("dd/MM/yyyy HH") + "*'"

Upvotes: 1

Related Questions