开发者

Selecting rows from DataTable by DateTime column (hours)

开发者 https://www.devze.com 2022-12-22 22:17 出处:网络
DatarowsForOneDay = dt.Select( dt.Columns[0].Caption + \"=\'\" + x.ToString(\"dd/MM/yyyy HH\") + \"\'\");
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

0

精彩评论

暂无评论...
验证码 换一张
取 消