问题
With the code below i get this error and need help with how to let method Load return List<B>
Cannot implicity convert type System.Collections.Generic.IEnumerable to 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;}
}
回答1:
Your query returns an IEnumerable
, while your method must return a List<B>
.
You can convert the result of your query to a list via the ToList()
extension method.
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;
}
}
The type of the list should be inferred automatically by the compiler. Were it not, you would need to call ToList<B>()
.
回答2:
You need to convert the enumeration to a list, there's an extension method to do that for you e.g. try this:
var result = from x in coll select new B {Prop1 = x.title, Prop2 = x.dept};
return result.ToList();
回答3:
You can't convert an object of a more generic type to a more specific.
Let's imagine, that we have a List of B and IEnumerable of B:
List<B> BList = ...
IEnumerable<B> BQuery = ...
You can do this:
IEnumerable<B> collection = BList;
But you can't do this:
List<B> collection = BQuery;
because collection is a more specific object, than IEnumerable.
So, you should use an extension method ToList() in your case:
(from x in coll
select new B
{
Prop1 = x.title,
Prop2 = x.dept
}
).ToList()
来源:https://stackoverflow.com/questions/13668648/cannot-implicity-convert-type-system-collections-generic-ienumerableb-to-syste