0

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

无法将类型“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

                    };
4

3 回答 3

4

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

如果你真的必须将它作为一个列表,那么将 () 放在整个 "From a in.... 以选择新的 xxx {};) 并首先在结果上调用 ToList() 。

否则,请执行“var searchresult = ....”,您仍然可以在“searchresult”变量上进行 foreach。

于 2012-07-27T20:35:18.330 回答
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();
于 2012-07-27T20:35:41.590 回答
1

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

于 2012-07-27T20:36:25.033 回答