简体   繁体   中英

Get the lowest year from LINQ query results

I am trying to find the earliest year from a group of rows returned by a LINQ query. The ActivationDate is stored as a datetime value in the DB.

I know that I can make a separate query to get just the date, but I would rather use the results from the existing query, as it is used for several other things.

IEnumerable<MonitoringPanel> panels = from rows in db.MonitoringPanels
                                      where rows.DealerEntity == dealerIDint
                                      select rows;

However this keeps throwing an error:

var testDate = panels.Min().ActivationDate;

Error:

System.ArgumentException was unhandled by user code.

It will throw an error even if I try to select the lowest PanelNumner (stored as an int), but the following does work:

var testDate = panels.FirstOrDefault().ActivationDate;

Solution

        DateTime testDate = (DateTime)panels.Min( thing => thing.ActivationDate);
        int lowYear = testDate.Year;

Unless the Enumerable is of a perimative type you need to add a lambda expression to tell it what property of the class to use. Try

var testDate = panels.Min(x => x.ActivationDate);

I think you need to tell the Min() method what to look for the Minimum of. Which field is the Minimum.

var testDate = panels.Min(panel => panel.ActivationDate);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM