用linq在一行中获取max + min [英] Get max + min in one line with linq

查看:118
本文介绍了用linq在一行中获取max + min的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改此方法,这样它也可以返回Max(t.StartTime)和Min(t.StartTime),只能在下面的一行中使用它?

How can I change this method so it also returns Max(t.StartTime) and Min(t.StartTime) with only using it in one line as below?

 public IQueryable<Timetable> GetTimetables()
    {
        return from t in _entities.Timetables
               select t;
    }

/ M

推荐答案

离开我的头顶(阅读:未经测试),并假定StartTime不可为空:

Off the top of my head (read: untested) and presuming StartTime is non-nullable:

public class TimetableWithMaxMin
{
    public Timetable Timetable { get; set; }
    public DateTime Max { get; set; }
    public DateTime Min { get; set; }
}

public IQueryable<TimetableWithMaxMin> GetTimetables()
{
    return from t in _entities.Timetables
           select new TimetableWithMaxMin
           {
               Timetable = t,
               Max = _entities.Timetables.Max(t => t.StartTime),
               Min = _entities.Timetables.Min(t => t.StartTime)
           };
}

当StartTime为空时,这会变得相当复杂。

This gets considerably more complicated when StartTime is nullable.

这篇关于用linq在一行中获取max + min的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆