gpt4 book ai didi

c# - 无法将类型 System.Collections.Generic.IEnumerable 隐式转换为 System.Collections.Generic.List

转载 作者:行者123 更新时间:2023-11-30 13:48:05 29 4
gpt4 key购买 nike

使用下面的代码我得到这个错误并且需要帮助如何让方法 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/

29 4 0