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?
Variabl开发者_如何学Ce x
type is DateTime
.
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);
}
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);
Use SUBSTRING or LIKE
or
dt.Columns[0].Caption + " LIKE '" + x.ToString("dd/MM/yyyy HH") + "*'"
Refer this:
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
精彩评论