How can I use Entity Framework to determine the maximum value of a column?

c# entity-framework max sql

Question

I may use the following T-SQL command to determine the maximum value of a column that includes integer data.

SELECT MAX(expression )
FROM tables
WHERE predicates;

Is it feasible to use Entity Framework to get the same outcome.

Consider the following model, which I have.

public class Person
{
  public int PersonID { get; set; }
  public int Name { get; set; }
  public int Age { get; set; }
}

How can I find out who is the oldest?

int maxAge = context.Persons.?
1
84
2/12/2015 6:02:17 PM

Accepted Answer

Try it.int maxAge = context.Persons.Max(p => p.Age);

And ensure that you haveusing System.Linq; the first line of your file

143
11/23/2015 7:08:23 PM

Popular Answer

I get an exception if the list is empty. This answer will consider the following problem:

int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow