无法将System.Collections.Generic.IEnumerable <t>类型隐式转换为System.Collections.Generic.List <b> </b> </b>

时间:2012-12-02 11:03:37

标签: c# generics ienumerable

使用下面的代码我得到此错误,需要有关如何让方法Load return List<B>

的帮助

无法将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;} 
}

3 个答案:

答案 0 :(得分:4)

您的查询返回IEnumerable,而您的方法必须返回List<B> 您可以通过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<B>()

答案 1 :(得分:3)

您需要将枚举转换为列表,有一种扩展方法可以为您执行此操作,例如试试这个:

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

答案 2 :(得分:2)

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

让我们想象一下,我们有一个B的列表和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()
相关问题