[英]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. 我试图从LINQ查询返回的一组行中找到最早的年份。 The ActivationDate is stored as a datetime value in the DB.
ActivationDate作为日期时间值存储在数据库中。
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: 即使我尝试选择最低的PanelNumner(存储为int格式),也会引发错误,但是以下操作确实有效:
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. 除非Enumerable为定理类型,否则您需要添加一个lambda表达式来告诉它要使用的类的属性。 Try
尝试
var testDate = panels.Min(x => x.ActivationDate);
I think you need to tell the Min()
method what to look for the Minimum of. 我认为您需要告诉
Min()
方法寻找最小值。 Which field is the Minimum. 哪个字段是最小值。
var testDate = panels.Min(panel => panel.ActivationDate);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.