2013-03-12 300 views
4

我试图从CSV导入中找到最大和最小DateTime s。在Linq组中查找最大和最小日期时间

我有这个从临时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的最高和最低值的最好方法是什么?

+0

注意'g.Min(C => C)'意味着找到你的第一个查询的最低匿名类型的全对象实例。没有为这种类型定义自然顺序,因此找到'.Min'或'.Max'没有任何意义。你也许是指'g.Min(c => c.StartTime)'? – mellamokb 2013-03-12 17:13:08

+0

@mellamokb我做了,p.s.w.g指出较低并解决了我的问题 – 2013-03-12 17:15:10

回答

7

尝试使用此

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

感谢p.s.w.g,完美 – 2013-03-12 17:14:19