【发布时间】:2014-11-22 08:00:46
【问题描述】:
我有 Linq 查询,我将它按 3 个字段分组,它返回结果我想根据键获取分组集合的字段,但是当我使用下面的查询时,它给了我错误
"当子查询不使用 EXISTS 引入时,选择列表中只能指定一个表达式。"
以下是我的查询
var patientResults = context.GetTable<PatientResult>().
Where(r =>
r.MeasurementTime < filterValues.DateTo.AddDays(1).Date
&& r.MeasurementTime >= filterValues.DateFrom
&& devicesFilter.Contains(r.DeviceId)).
GroupBy(x => new { x.MeasurementTime, x.Model, x.DeviceId });
var patientResults12 =patientResults.Select(x => new PatientMeasurementResult()
{
MeasurementTime = x.Key.MeasurementTime,
Model = x.Key.Model,
DeviceId = x.Key.DeviceId,
PatientId = x.FirstOrDefault().PatientId,
PatientName = x.FirstOrDefault().PatientName
});
我想要 2 个元素 PatientId 和 PatientName,我不想将它们包含在 groupby 中 如果我只为 PatientId 或 PatientName 提供 FirstOrDefault() ,它工作正常,但是当我为两者都提供时,它会给出上述错误。
【问题讨论】:
-
你为什么在 x 上做 FirstOrDefault。为什么不能做 x.Key.Patientid 和 x.Key.Patientname?
-
PatientId 和 PatientName 是非关键元素,因此不能在 group by 中使用它们,因此它们不能作为 key 也不能用作 x.key.patientid,重要的是它们可以为 null
-
你的 PatientResult 类的结构是什么。