简体   繁体   中英

How do I fix an error message of “Cannot implicitly convert type Generic.IEnumerable<type>' to 'Generic.List<type>”

Why do I get this error message:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'

when I build this code:

 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

                    };

The type returned from the LINQ statement is IEnumerable, not a List.

if you really MUST have it as a List then put () around the whole "From a in.... to select new xxx {};) and call ToList() on the result first.

Otherwise do "var searchresult = ...." and you can foreach on your "searchresult" variable still.

You may just need to wrap your linq with some parentheses and call .ToList on the result:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM