阅读here和here,我理解查询语法和方法扩展几乎是语法差异。但现在,我有一个包含测量数据的数据结构,并希望确定百分位数。我写道:
var ds = (from device in dataSet.devices
where !device.paramValues[i].Equals(double.NaN)
select device.paramValues[i]).OrderBy(val => val);
double median = percentile(ds as IOrderedEnumerable<double>, 0.5);
一切正常。 ds的类型为System.Linq.OrderedEnumerable<double,double>
令我困惑的是用查询语法编写整个内容:
var ds = (from device in dataSet.devices
where !device.paramValues[i].Equals(double.NaN)
orderby device.paramValues[i]
select device.paramValues[i]);
double median = percentile(ds as IOrderedEnumerable<double>, 0.5);
现在,ds的类型为System.Linq.Enumerable.WhereSelectEnumerableIterator<Dataset.DeviceData,double>
,并且对百分位函数的调用失败。
还不确定我在这里缺少什么... - 没有特别的理由为什么我更喜欢第二种语法,但我想了解其中的差异......感谢您的帮助!
答案 0 :(得分:5)
from device in dataSet.devices
where !device.paramValues[i].Equals(double.NaN)
select device.paramValues[i]
转换为如下方法:
dataSet.devices
.Where(device => !device.paramValues[i].Equals(double.NaN))
.Select(device => device.paramValues[i]);
添加OrderBy
来电
dataSet.devices
.Where(device => !device.paramValues[i].Equals(double.NaN))
.Select(device => device.paramValues[i])
.OrderBy(val => val);
另一个查询
from device in dataSet.devices
where !device.paramValues[i].Equals(double.NaN)
orderby device.paramValues[i]
select device.paramValues[i];
转换为
dataSet.devices
.Where(device => !device.paramValues[i].Equals(double.NaN))
.OrderBy(device => device.paramValues[i])
.Select(device => device.paramValues[i]);
正如您所看到的,它不是完全相同的方法链,那是因为您获得了不同的对象。内容是相同的,但返回的类型不是。
答案 1 :(得分:2)
首先看另一个答案。以下是对查询语法的相同操作:
from device in dataSet.devices
where !device.paramValues[i].Equals(double.NaN)
select device.paramValues[i] into x //into syntax
orderby x
select x;