How to find max in datacolumn datetime?

I have a DataColumn DateTime, I would like to know how I can only have an earlier date (min) and a later date (max).

thanks

+6
source share
5 answers

This will give what you are looking for:

// Initial Code for Testing DataTable dt = new DataTable(); dt.Columns.Add("Dates", typeof(DateTime)); dt.Rows.Add(new object[] { DateTime.Now }); dt.Rows.Add(new object[] { DateTime.Now.AddDays(1) }); dt.Rows.Add(new object[] { DateTime.Now.AddDays(2) }); 

This is the code you would use:

 // Actual Code DataColumn col = dt.Columns[0]; // Call this the one you have DataTable tbl = col.Table; var first = tbl.AsEnumerable() .Select(cols => cols.Field<DateTime>(col.ColumnName)) .OrderBy(p => p.Ticks) .FirstOrDefault(); var last = tbl.AsEnumerable() .Select(cols => cols.Field<DateTime>(col.ColumnName)) .OrderByDescending(p => p.Ticks) .FirstOrDefault(); 
+4
source
 object maxDate = dataTable.Compute("MAX(TheDateColumnName)", null); object minDate = dataTable.Compute("MIN(TheDateColumnName)", null); 
+13
source

To add to the answer from Kyle, isn’t it easier to do:

for the largest date:

 var last = tbl.AsEnumerable() .Max(r => r.Field<DateTime>(col.ColumnName)); 

and before:

 var first = tbl.AsEnumerable() .Min(r => r.Field<DateTime>(col.ColumnName)); 
+2
source

Just return the DateTime list from your DataColumn. The Foreach line in your DataColumn adds the current item to the DateTime list.

List<DateTime> and use the Sort method, then get the first and last values.

Depending on your version of the frame, use the above for 2.0 , for >=3.5 you can use Max and Min or C linq .OrderByDesc(p => pX).FirstOrDefault(); on your datetime list

0
source
 DataTable dt = new DataTable("MyDataTable"); DataColumn dc = new DataColumn("DateColumn"); dc.DataType = typeof(DateTime); dt.Columns.Add(dc); for (int i = 0; i <= 5; i++) { DataRow newRow = dt.NewRow(); newRow[0] = DateTime.Now.AddDays(i); dt.Rows.Add(newRow); } DateTime maxDate = Convert.ToDateTime( ((from DataRow dr in dt.Rows orderby Convert.ToDateTime(dr["DateColumn"]) descending select dr).FirstOrDefault()["DateColumn"] ) ); DateTime minDate = Convert.ToDateTime( ((from DataRow dr in dt.Rows orderby Convert.ToDateTime(dr["DateColumn"]) ascending select dr).FirstOrDefault()["DateColumn"] ) ); 
0
source

Source: https://habr.com/ru/post/902576/


All Articles