无法将类型System.Collections.Generic.IEnumerable 转换为System.Collections.Generic.List
使用下面的代码我得到这个错误,并需要帮助如何让方法Load返回List
无法将System.Collections.Generic.IEnumerable类型转换为System.Collections.Generic.List
public class A { public List Load(Collection coll) { List 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;} }
您的查询返回IEnumerable
,而您的方法必须返回List
。
您可以通过ToList()
扩展方法将查询结果转换为列表。
public class A { public List Load(Collection coll) { List list = (from x in coll select new B {Prop1 = x.title, Prop2 = x.dept}).ToList(); return list; } }
列表的类型应由编译器自动推断。 如果不是,您需要调用ToList()
。
你需要将枚举转换为列表,有一个扩展方法为你做这个,例如试试这个:
var result = from x in coll select new B {Prop1 = x.title, Prop2 = x.dept}; return result.ToList();
您不能将更通用类型的对象转换为更具体的类型。
让我们想象一下,我们有一个B的列表和B的IEnumerable:
List BList = ... IEnumerable BQuery = ...
你可以这样做:
IEnumerable collection = BList;
但你不能这样做:
List collection = BQuery;
因为集合是一个比IEnumerable更具体的对象。
因此,您应该在您的情况下使用扩展方法ToList():
(from x in coll select new B { Prop1 = x.title, Prop2 = x.dept } ).ToList()