Link to home
Start Free TrialLog in
Avatar of dblankman
dblankman

asked on

How to write a select year(max(datefield) in EntitySQL in c# entity framework

I have the following sql query:  

SELECT year(max(eventdate)
FROM TurtleEvent

How do I write this in EntitySQL
Avatar of Gustav Brock
Gustav Brock
Flag of Denmark image

Retrieve your eventdates (here it is a list), extract the year from the dates, and find the maximum year:
List<DateTime> list = new List<DateTime>();
list.Add(new DateTime(2012, 2, 3));
list.Add(new DateTime(2011, 12, 23));
list.Add(new DateTime(2014, 10, 5));
list.Add(new DateTime(2013, 4, 13));

int year = list.Select(d => d.Year).Max();  

Console.WriteLine("Max. year: " + year.ToString());

// Result: Max. year: 2014

Open in new window

Or, with no Lambda:
int year = (from d in list select d).Max().Year;

Open in new window

/gustav
Avatar of dblankman
dblankman

ASKER

I am getting the date from a database query. Normally I would do something like

ste is a reference to entities

var varDate =( from d in ste.TurtleEvent
                         select d)
however, that gets me a whole row. How do I populate the list you propose from a database query where the date field is a sql datetime?
Hi,
Pls try this..

TurtleEvent.Eventdate.MAX().ToString("YYYY")

Open in new window


Hope it helps!
That would be:
DateTime maxDate = (from event in ste.TurtleEvent select event.eventdate).Max();

Open in new window

or:
int year = (from event in ste.TurtleEvent select event.eventdate).Max().Year;

Open in new window

/gustav
When I try either of these I get an error saying that "from" does not exist in this context. It seems that the "from" syntax only works with a var.
Hi,
Any luck with mine?

Thank you.
Pawan
Then try with the Lambda syntax:

int year = ste.TurtleEvent.Select(d => d.Year).Max();

Open in new window

Or perhaps something else is going on.

/gustav
Pawan, in what context would this go.  TurtleEvent.Eventdate.MAX().ToString("YYYY"). ?
Hi,
Pls try like..

int year = ste.TurtleEvent.Eventdate.MAX().Year;

Open in new window


Hope it helps!
ASKER CERTIFIED SOLUTION
Avatar of Gustav Brock
Gustav Brock
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks, that helps a lot.
You are welcome!

/gustav