如何修复"Cannot implicitly convert type Generic.IEnumerable<type>' to 'Generic.List<type>"



为什么我会收到这个错误消息:

无法将类型"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
                    };

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

如果你真的必须把它作为一个列表,那么把()放在整个"From a in….to select new xxx{};"周围,然后首先对结果调用ToList()。

否则,执行"var searchresult=….",您仍然可以对"searchresult"变量进行foreach。

您可能只需要用一些括号包装您的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();

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

相关内容

最新更新