[英]Why do I get 'cannot convert type 'IEnumerable<myType>' to 'myType' on this LINQ query?
Object is simple, it's a rate of pay: 对象很简单,它是一个支付率:
public class RateOfPay
{
public decimal Rate { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
}
and I'm trying to get it like this: 我正在尝试这样获得它:
IEnumerable<T> rates = GetRates();
/*
actual collection is DevExpress XPCollection<RateOfPay>
which implements IEnumerable<T>
*/
var rate = from r in rates where r.End == null select r; // err here
It's odd because the intellisense works fine on r, but it's saying that r is an IEnumerable collection? 这很奇怪,因为intellisense在r上可以正常工作,但是说r是IEnumerable集合吗?
What am I missing? 我想念什么?
It is a collection, it's an IEnumerable().Where(rate => rate.End == null) which is all rates that match that criteria. 这是一个集合,它是IEnumerable()。Where(rate => rate.End == null),它是所有符合该条件的费率。
You're missing the .FirstOrDefault() on your IEnumerable, can't tell you the statement query syntax though.. 您在IEnumerable上缺少.FirstOrDefault(),但是无法告诉您语句查询语法。
Should look like 应该看起来像
var rate = rates.FirstOrDefault(r => r.End == null);
In this code sample the IEnumerable<T>
collection is not bound to a particular type. 在此代码示例中,
IEnumerable<T>
集合未绑定到特定类型。 Hence there is no way to call the End
property on the value. 因此,无法对值调用
End
属性。 Is there a type in the code? 代码中是否有类型?
If not the following could fix the problem 如果不是这样,则可以解决问题
var rate = from r in rates.Cast<RateOfPay>() where r.End == null select r;
If on the other hand there is just a type and you are looking to have rate
be a single value then try the following. 另一方面,如果只有一种类型,并且您希望让
rate
为单个值,请尝试以下操作。
var filtered = from r in rates where r.End == null select r;
RateOfPay v1 = filtered.Single(); // If only 1 should ever match
RateOfPay v2 = filtered.First(); // if several could match and you just want 1
var rate = from r in rates where r.End == null select r;
var rate = from r in rate in r.End == null选择r; // err here
//在这里错误
Hmmmm.... Is rate
really declared ar var
, or is that really `Rate rate =' ?? 嗯...。
rate
是真的声明为var
,还是真的是“ Rate rate =”?
The reason I ask, is because the linq query is going to return an IEnumerable (with likely just one item). 我问的原因是因为linq查询将返回IEnumerable(可能只有一项)。 You probably actually want:
您实际上可能想要:
Rate rate = (from r in rates where r.End == null select r).First();
which could be reduced to just: 可以简化为:
Rate rate = rates.First(r=>r.End == null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.