如何修复“无法将类型Generic.IEnumerable <type>'隐式转换为'Generic.List <type>'</type> </type>的错误消息

时间:2012-07-27 20:32:46

标签: c# asp.net linq list generics

为什么会出现此错误消息:

  

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

当我构建此代码时:

 List<BALHotelList> searchresult=from a in bh
                join b in hr on a.HotelCode equals b.hotelCode
                orderby a.HotelName
                select new BALHotelList
                    {
                       HotelCode= a.HotelCode,
                       ImageURL_Text = a.ImageURL_Text,
                       HotelName = a.HotelName,
                       StarRating = a.StarRating,
                       HotelAddress = a.HotelAddress,
                       Destination = a.Destination,
                       Country = a.Country,
                       HotelInfo = a.HotelInfo,
                       Latitude = a.Latitude,
                       Longitude = a.Longitude,
                       totalPrice = b.totalPrice,
                       totalPriceSpecified = b.totalPriceSpecified,
                       totalSalePrice = b.totalSalePrice,
                       totalSalePriceSpecified = b.totalSalePriceSpecified,
                       rooms = b.rooms

                    };

3 个答案:

答案 0 :(得分:4)

从LINQ语句返回的类型是IEnumerable,而不是List。

如果你真的必须把它作为一个List然后把()放在整个“从一个......来选择新的xxx {};”并首先在结果上调用ToList()。

否则请执行“var searchresult = ....”并且您仍可以使用“searchresult”变量进行操作。

答案 1 :(得分:3)

您可能只需要用一些括号包装你的linq并在结果上调用.ToList:

List<BALHotelList> searchresult= (from a in bh
            join b in hr on a.HotelCode equals b.hotelCode
            orderby a.HotelName
            select new BALHotelList
                {
                   HotelCode= a.HotelCode,
                   ImageURL_Text = a.ImageURL_Text,
                   HotelName = a.HotelName,
                   StarRating = a.StarRating,
                   HotelAddress = a.HotelAddress,
                   Destination = a.Destination,
                   Country = a.Country,
                   HotelInfo = a.HotelInfo,
                   Latitude = a.Latitude,
                   Longitude = a.Longitude,
                   totalPrice = b.totalPrice,
                   totalPriceSpecified = b.totalPriceSpecified,
                   totalSalePrice = b.totalSalePrice,
                   totalSalePriceSpecified = b.totalSalePriceSpecified,
                   rooms = b.rooms

                }).Tolist();

答案 2 :(得分:1)

如果你想要一个列表,你需要将Linq查询包装在括号中并调用.ToList()