views:

146

answers:

2

Hello

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

A: 

I don't know if this is applicable to Entity framework but with linq it's something like this

 public IQueryable<Timetable> GetTimetables()
    {
        return from t in _entities.Timetables
               select new {maxt = Max(t.StartTime), mint = Min(t.StartTime)};
    }
Omu
seems like there is some syntax issues
molgan
He forgot the `t =>`, as in `t => t.StartTime`. See http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#maxSimple
Craig Stuntz
t = > is used for lambdas, that would something like this GetTimeTables().Select(t => new {maxt = Max(t.StartTime), mint = Min(t.StartTime)})
Omu
Max and Min both **require** an expression. See the link I posted, Omu.
Craig Stuntz
+1  A: 

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

This gets considerably more complicated when StartTime is nullable.

Craig Stuntz