【问题标题】:Cannot implicity convert type System.Collections.Generic.IEnumerable<B> to System.Collections.Generic.List<B>无法将类型 System.Collections.Generic.IEnumerable> 隐式转换为 System.Collections.Generic.List<B>
【发布时间】:2012-12-02 11:03:36
【问题描述】:

使用下面的代码,我得到了这个错误,需要帮助如何让方法 Load 返回List&lt;B&gt;

不能将 System.Collections.Generic.IEnumerable 类型隐式转换为 System.Collections.Generic.List

public class A
    {
      public List<B> Load(Collection coll)
      {
        List<B> list = from x in coll select new B {Prop1 = x.title, Prop2 = x.dept};
        return list;
      }
    }

public class B
{
  public string Prop1 {get;set;}
  public string Prop2 {get;set;} 
}

【问题讨论】:

  • 必须是列表吗?请记住,这会实现查询。

标签: c# generics ienumerable


【解决方案1】:

您的查询返回一个IEnumerable,而您的方法必须返回一个List&lt;B&gt;
您可以通过ToList() 扩展方法将查询结果转换为列表。

public class A
{
   public List<B> Load(Collection coll)
   {
       List<B> list = (from x in coll select new B {Prop1 = x.title, Prop2 = x.dept}).ToList();
       return list;
   }
}

列表的类型应该由编译器自动推断。如果不是,您需要致电ToList&lt;B&gt;()

【讨论】:

    【解决方案2】:

    您需要将枚举转换为列表,有一个扩展方法可以为您做到这一点,例如试试这个:

        var result = from x in coll select new B {Prop1 = x.title, Prop2 = x.dept};
        return result.ToList();
    

    【讨论】:

      【解决方案3】:

      您无法将更通用类型的对象转换为更具体的对象。

      假设我们有一个 B 的 List 和 B 的 IEnumerable:

      List<B> BList = ...
      IEnumerable<B> BQuery = ...
      

      你可以这样做:

      IEnumerable<B> collection = BList;
      

      但你不能这样做:

      List<B> collection = BQuery;
      

      因为集合是一个比 IEnumerable 更具体的对象。

      因此,您应该在您的情况下使用扩展方法 ToList():

      (from x in coll
      select new B 
        {
          Prop1 = x.title, 
          Prop2 = x.dept
        }
      ).ToList()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-07
        • 2013-05-14
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        相关资源
        最近更新 更多