I've been struggling to use the Max function in my LINQ expression. I want to select various properties from multiple SQL tables for the last year (the "max" year). The red squiggly tells me that my int? does not contain a definition for Max and Enumerable.Max (the function I want) requires a receiver type of IEnumerable< int>. I'm completely new to all this stuff, and while I've searched the web, I can't come up with a clear explanation of what I need to do to fix this. I figured it was an SQL table and it would go through the rows as normal SQL queries do.
My code, which I've tried many variations of:
var otherPrograms = (from hm in db.HabitatManagement
join svy in db.Survey on hm.SurveyID equals svy.SurveyID
join iu in db.InventoryUsers on hm.UserID equals iu.UserID
join pt in db.ProgramType on hm.ProgramTypeID equals pt.ProgramTypeID
where pt.Program != "State Agency Public Land Programs"
&& pt.Program != "State Agency Private Land Programs"
&& svy.ReportingYear.Max()
select new
{
iu.StateID,
hm.ProgramTypeID,
pt.Program,
svy.ReportingYear
})
.Distinct()
.Select(x => new { x.StateID, x.Program, x.ProgramTypeID, x.ReportingYear, DisplayText = x.ReportingYear.ToString() + ", " + x.StateID.ToString() + ", " + x.Program.ToString() })
.OrderBy(x => x.StateID);
I have also tried a nested query to achieve the same thing (not sure I even did it right):
&& svy.ReportingYear = (from svy in db.Survey
select svy.ReportingYear.Max())
When I look at the definition for the ReportingYear property it looks like so:
public Nullable<int> ReportingYear {get; set;}
I'm pretty sure the issue is that it's not an IEnumerable< int> so how do I make it one without messing with my SQL tables?
Nullable
, by definition, represents a value type that can be assigned null . Meaning the property holds a single value, not a Collection
.
From your code it looks like you want to get the maximum of a set of years stored in ReportingYear
, so you should probably define ReportingYear
as some sort of a collection, like List<int>
.
public List<int> ReportingYear { get; set; }
And if being nullable is important, create a list of nullable integers , as follows:
public List<int?> NullableReportingYear { get; set; }
Before the where add the following, then use maxYear instead of your svy.ReportingYear.Max()
let maxYear = (from svy in db.Survey
where svy.MaxYear != null
select (int)svy.MaxYear).Max()
So...
&& svy.ReportingYear.Max()
Needs to be changed to
&& svy.ReportingYear != null && svy.ReportingYear == maxYear
or
&& (svy.ReportingYear == null || svy.ReportingYear == maxYear)
This should give the max ReportingYear
value in the Survey
collection/table:
int max = (from svy in db.Survey
where svy.ReportingYear.HasValue
select svy.ReportingYear.Value).Max();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.