Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have DataTable having DataTime type column, i want to select records from table on hour basic from Datetime column field.

want same result of Sql Query " select ColumnName from TableName where datepart(HOUR,ColumName)=09"

09 is hour value.

If have any idea please share.
Posted
Comments
Have you tried anything for that?
SachinSutar 5-Jun-14 2:19am    
I tried but it works only for date not for time part.

var rows = ObjTargetRange.RangeDataTable.Select(ObjFromRange.DataSource + ">= #" + StartVal + "# AND " + ObjFromRange.DataSource + " <= #" + EndVal + "#");

You need to reference the System.Data.DataSetExtensions assembly and use the System.Data namespace.

C#
dt =dt.AsEnumerable()
       .Where(r=>r.Field<datetime>("DateCol").Month ==9)
       .CopyToDataTable();


And read the documentation for .NET Framework 3.5
Creating a DataTable From a Query (LINQ to DataSet)[^]
C#
below is sample code from above reference 
// Bind the System.Windows.Forms.DataGridView object 
// to the System.Windows.Forms.BindingSource object.
dataGridView.DataSource = bindingSource;

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable orders = ds.Tables["SalesOrderHeader"];

// Query the SalesOrderHeader table for orders placed  
// after August 8, 2001.
IEnumerable<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
    select order;

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

// Bind the table to a System.Windows.Forms.BindingSource object,  
// which acts as a proxy for a System.Windows.Forms.DataGridView object.
bindingSource.DataSource = boundTable;
 
Share this answer
 
v4
Comments
SachinSutar 5-Jun-14 2:27am    
Thanks DamithSL. it works. Get desired result.
DamithSL 5-Jun-14 2:33am    
You are welcome! :-)
That query works perfectly well for me when I use 9 as the value.

09 seems to indicate you are storing the data as text and not datetime in which case you are screwed until you change the format to datetime.
 
Share this answer
 
Comments
SachinSutar 5-Jun-14 2:10am    
In sql 09 is also ok it works perfectly but i want to execute it in c# on the datatable (may be using some Linq) not in datatbase table.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900