[英]Linq FirstOrDefault returning multiple
I am having a strange issue in which a linq statement is returning multiple entities even though it has .FirstOrDefault()
. 我遇到一个奇怪的问题,即使linq语句具有
.FirstOrDefault()
它也会返回多个实体。
var endlog = from e in endLogs
where e.user_id == log.user_id && e.end_time <= log.start_time
group e by e.end_time into g
select g.OrderByDescending(x => x.end_time).FirstOrDefault();
user_state_log eLog = endlog.SingleOrDefault();
What this is doing is selecting the log with the most recent end time compared to the supplied log
. 这是在选择与提供的
log
相比具有最近结束时间的log
。 I get an exception on user_state_log eLog = endlog.SingleOrDefault()
stating that there is more than one entity in the variable. 我在
user_state_log eLog = endlog.SingleOrDefault()
上user_state_log eLog = endlog.SingleOrDefault()
异常,指出该变量中有多个实体。 Any ideas? 有任何想法吗?
Are you sure you mean to use group e by
instead of orderby
? 您确定要使用
group e by
而不是orderby
吗? There is a chance that the grouping will contain multiple entities. 分组有可能包含多个实体。
Your FirstOrDefault
is applying to the result of select
, which occurs once for every group ( g
). 您的
FirstOrDefault
将应用于select
的结果,该结果对于每个组( g
)都会发生一次。 I believe the result is every value in endlog
will be a single item rather than a group. 我相信结果是
endlog
每个值endlog
将是一个项目而不是一个组。
You might have intended for the FirstOrDefault
to apply to the query rather than the projection ( select
): 您可能希望将
FirstOrDefault
应用于查询而不是投影( select
):
var endlog = (from e in endLogs
where e.user_id == log.user_id && e.end_time <= log.start_time
group e by e.end_time into g
select g.OrderByDescending(x => x.end_time)).FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.