【问题标题】:Why do I get 'cannot convert type 'IEnumerable<myType>' to 'myType' on this LINQ query?为什么我在此 LINQ 查询中得到“无法将类型 'IEnumerable<myType>' 转换为 'myType'?
【发布时间】:2010-08-20 20:37:32
【问题描述】:

对象很简单,就是工资率:

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

这很奇怪,因为智能感知在 r 上运行良好,但它说 r 是一个 IEnumerable 集合?

我错过了什么?

【问题讨论】:

  • T 是什么?你的意思是IEnumerable&lt;RateOfPay&gt; rates = GetRates();

标签: c# linq .net-3.5


【解决方案1】:

它是一个集合,它是一个 IEnumerable().Where(rate => rate.End == null),它是符合该条件的所有速率。

您的 IEnumerable 上缺少 .FirstOrDefault(),但无法告诉您语句查询语法..

应该是这样的

var rate = rates.FirstOrDefault(r => r.End == null);

【讨论】:

    【解决方案2】:

    在此代码示例中,IEnumerable&lt;T&gt; 集合未绑定到特定类型。因此,无法调用该值的 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
    

    【讨论】:

      【解决方案3】:

      var rate = from r in rates where r.End == null select 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);
      

      【讨论】:

        猜你喜欢
        • 2012-07-27
        • 1970-01-01
        • 1970-01-01
        • 2012-11-29
        • 2017-07-10
        • 2013-06-11
        • 2021-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多