,c#,list,linq,types,ienumerable"/>

首页 > 解决方案 > C# SelectMany 错误“无法隐式转换类型'System.Collections.Generic.List' 到 'System.Collections.Generic.List'"

问题描述

在 linq 内部,Select我有一个SelectMany抛出错误

C# SelectMany 错误“无法将类型 ' System.Collections.Generic.List<char>' 隐式转换为 ' System.Collections.Generic.List<List>'”

List<Hotel> hotelList = reservations
    .GroupBy(i => i.hotelID)
    .Select(c => new Hotel()
    {
        HotelID = c.First().HotelID,
        HotelName = c.First().HotelName,
        HotelAddress1 = c.First().HotelAddress1,
        HotelAddress2 = c.First().HotelAddress2,
        HotelAddress3 = c.First().HotelAddress3,
        HotelCity = c.First().CCCity,
        HotelPostalCode = c.First().CCZip,
        ReservationNumbers = c.SelectMany( i => i.ReservationNumber).Distinct().ToList()

    }).ToList();

SelectMany自动将其转换为 a IEnumerable<char>,然后ToList将其转换为List<Char>

i.ReservationNumber属于类型StringReservationNumbers属于类型List<string>c属于类型IGrouping<Reservation, int>

什么是强制转换为List<string>或如何SelectMany返回的方法IEnumerable<string>

标签: c#listlinqtypesienumerable

解决方案


如果i.ReservationNumber是类型String,你需要简单地写

ReservationNumbers = c.Select( i => i.ReservationNumber).Distinct().ToList()

SelectMany尝试遍历 的元素ReservationNumber,其中,being String,是IEnumerable<char>


推荐阅读