C# 如何修复“无法将类型Generic.IEnumerable隐式转换为”Generic.List“的错误消息
为什么我会收到此错误消息: 无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List” 构建此代码时:C# 如何修复“无法将类型Generic.IEnumerable隐式转换为”Generic.List“的错误消息,c#,asp.net,linq,list,generics,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.Hot
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 如果你真的必须把它列为一个列表,那么把整个列表放在一个。。。。选择新的xxx{};然后先打电话给ToList查询结果
否则执行var searchresult=。。。。您仍然可以在searchresult变量上使用foreach。您可能只需要用括号将linq括起来,然后调用。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.为什么不使用var searchresult=呢?因为var范围仅限于该方法。这很重要吗?那就在这条路的尽头扔一个。托利斯特query@rahularyansharma当var用于匿名类型时,匿名类型不能离开该方法。对于真正的类型,var只是键入完整类型名的语法糖。var仅限于作用域,我想将其用作globallyRight,所以按照我所说的,在生成的IEnumerable上显式调用ToList