tags:

views:

245

answers:

4
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.

+1  A: 

Use SUBSTRING or LIKE

or

dt.Columns[0].Caption + " LIKE '" + x.ToString("dd/MM/yyyy HH") + "*'"
igor
Невозможно выполнить операцию "Like" над System.DateTime и System.String. в System.Data.BinaryNode.SetTypeMismatchError(Int32 op, Type left, Type right)
nCdy
да елки палки ;) 1) Don't use Caption (look for Value or something else)2) x1 = new DateTime(x.day, x.month, x.year, x.hour, 0, 0);x2 = x1.AddHours(1);use .Caption >= x1 and .Caption < x2
igor
some small mistake, use so (year first): new DateTime(x.YEAR, x.month, x.day, x.hour, 0, 0)
igor
dt.Select("'"+dt.Columns[0].Caption + "' = '" + x.ToString("dd/MM/yyyy HH") + "'"); That was so foolish from me >_<
nCdy
+1  A: 

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);
João Angelo
How to convert rows ot DataRows[] ?
nCdy
@nCdy, you would use the `ToArray` extension method. I updated the example to use an array.
João Angelo
+2  A: 

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);            
}
Adeel