在Linq分组中查找最大和最小的DateTime

5

我正在尝试从CSV导入中查找DateTime的最大值和最小值。

我有以下代码来导入临时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
                    };

这很好。然后我想对数据进行分组,并显示开始时间和结束时间,即相应字段的最小/最大值。

到目前为止,我有:

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

我曾认为g.Ming.Max可以分别给出每个时间表(按索引分组)中最低和最高的DateTime

但是这并不起作用...那么在一个分组内找到最高和最低的DateTime值的最佳方法是什么?


1
请注意,g.Min(c => c) 表示在第一个查询中查找整个匿名类型对象的最小值。对于此类型没有定义自然排序,因此查找 .Min.Max 没有意义。您是否想要 g.Min(c => c.StartTime) - mellamokb
@mellamokb 我已经这样做了,正如p.s.w.g所指出并解决了我的问题。 - Gordon Copestake
1个回答

11

试着使用这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接