![](/img/trans.png)
[英]How can I convert an IEnumerable<MyType> into a MyList<MyType>?
[英]Why do I get 'cannot convert type 'IEnumerable<myType>' to 'myType' on this LINQ query?
对象很简单,它是一个支付率:
public class RateOfPay
{
public decimal Rate { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
}
我正在尝试这样获得它:
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
这很奇怪,因为intellisense在r上可以正常工作,但是说r是IEnumerable集合吗?
我想念什么?
这是一个集合,它是IEnumerable()。Where(rate => rate.End == null),它是所有符合该条件的费率。
您在IEnumerable上缺少.FirstOrDefault(),但是无法告诉您语句查询语法。
应该看起来像
var rate = rates.FirstOrDefault(r => r.End == null);
在此代码示例中, IEnumerable<T>
集合未绑定到特定类型。 因此,无法对值调用End
属性。 代码中是否有类型?
如果不是这样,则可以解决问题
var rate = from r in rates.Cast<RateOfPay>() where r.End == null select r;
另一方面,如果只有一种类型,并且您希望让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 rate in r.End == null选择r; //在这里错误
嗯...。 rate
是真的声明为var
,还是真的是“ Rate rate =”?
我问的原因是因为linq查询将返回IEnumerable(可能只有一项)。 您实际上可能想要:
Rate rate = (from r in rates where r.End == null select r).First();
可以简化为:
Rate rate = rates.First(r=>r.End == null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.