使用下面的代码,我收到此错误并需要有关如何让方法 Load 返回 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;}
}
最佳答案
您的查询返回 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>()
。关于c# - 无法将 System.Collections.Generic.IEnumerable<T> 类型隐式转换为 System.Collections.Generic.List<B>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13668648/