【问题标题】:Find max and min DateTime in Linq group在 Linq 组中查找最大和最小日期时间
【发布时间】:2013-03-12 17:07:58
【问题描述】:

我正在尝试从 CSV 导入中找到最大和最小 DateTimes。

我有这个从 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
                    };

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

到目前为止,我有这个:

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(按索引分组)

但是这不起作用...在组中找到最高和最低 DateTimes 值的最佳方法是什么?

【问题讨论】:

  • 请注意,g.Min(c =&gt; c) 表示在您的第一个查询中找到匿名类型的整个对象实例的最小值。没有为这种类型定义自然顺序,因此查找.Min.Max 没有任何意义。你的意思是g.Min(c =&gt; c.StartTime)吗?
  • @mellamokb 我做到了,p.s.w.g 指出更低并解决了我的问题

标签: c# asp.net linq entity-framework


【解决方案1】:

试试这个

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

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多