Find max and min DateTime in Linq group

asp.net c# entity-framework linq

Question

I'm trying to find the max and min DateTimes from a CSV import.

I have this to import the data from the temp DataTable:

var tsHead = from h in dt.AsEnumerable()
         select new
                    {
                        Index = h.Field<string>("INDEX"),
                        TimeSheetCategory = h.Field<string>("FN"),
                        Date = DdateConvert(h.Field<string>("Date")),
                        EmployeeNo = h.Field<string>("EMPLOYEE"),
                        Factory = h.Field<string>("FACTORY"),
                        StartTime = DdateConvert(h.Field<string>("START_TIME")), //min
                        FinishTime = DdateConvert(h.Field<string>("FINISH_TIME")), //max
                    };

Which works fine. I then want to group the data and show the Start time and finish time which is the min / max of the respective fields.

So far I have this:

var tsHeadg = from h in tsHead
                      group h by h.Index into g //Pull out the unique indexes
                      let f = g.FirstOrDefault() where f != null
                      select new
                                 {
                                     f.Index,
                                     f.TimeSheetCategory,
                                     f.Date,
                                     f.EmployeeNo,
                                     f.Factory,
                                     g.Min(c => c).StartTime, //Min starttime should be timesheet start time
                                     g.Max(c => c).FinishTime, //Max finishtime should be timesheet finish time
                                 };

With the thinking that g.Min and g.Max would give me the lowest and highest DateTime for each timesheet (grouped by index)

This doesn't work however... Whats the best way of finding the highest and lowest value of DateTimes within a group?

1
4
3/12/2013 5:22:10 PM

Accepted Answer

Try using this

var tsHeadg = 
    (from h in tsHead
     group h by h.Index into g //Pull out the unique indexes
     let f = g.FirstOrDefault() 
     where f != null
     select new
     {
         f.Index,
         f.TimeSheetCategory,
         f.Date,
         f.EmployeeNo,
         f.Factory,
         MinDate = g.Min(c => c.StartTime),
         MaxDate = g.Max(c => c.FinishTime),
     });
9
3/12/2013 5:10:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow