无法将类型'System.Collections.Generic.List <string>'隐式转换为'System.Collections.Generic.IEnumerable <turon.model.products_products>

时间:2015-05-22 08:46:44

标签: c# list ienumerable

public IEnumerable<Products_Products> getprod()
{
    var db = new Model.atengturonDBEntities();
    IEnumerable<Products_Products> x = new List<Products_Products>();
    var test = (from name in db.Products_Products select 
                    name.ProductName).ToList();
    x = test;
    return x;
}

为什么我收到此错误?我也尝试将所有'IEnumerable'改为'List',救救我!谢谢:))

  

无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'。存在显式转换(您是否错过了演员?)

3 个答案:

答案 0 :(得分:4)

Error message is quite clear. Your LINQ query returns collection of string, because you're selecting name.ProductName, but your method is declared to return collection of Products_Products.

Change your LINQ query to return not just ProductName but the product itself:

IEnumerable<Products_Products> x = new List<Products_Products>();
var test = (from name in db.Products_Products select 
                name).ToList();

(can also be replaced with just db.Products_Products.ToList().

Or change your method to return IEnumerable<string>

public IEnumerable<string> getprod()

答案 1 :(得分:2)

The Lambada expression is getting the ProductName from each product and collect it as a collection of strings.. i suggest you to change it to:

return (from name in db.Products_Products select 
             name).ToList();

答案 2 :(得分:2)

您可以使用.FirstOrDefaultFirst它始终解决我的问题