Faris Kapo
Faris Kapo

Reputation: 376

C# SelectMany error " Cannot Implicitly convert type 'System.Collections.Generic.List<char>' to 'System.Collections.Generic.List<List>' "

Inside of a linq Select I have a SelectMany which is throwing an error

C# SelectMany error " Cannot Implicitly convert type 'System.Collections.Generic.List<char>' to '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 automatically converts it to a IEnumerable<char>, and then ToList turns that to List<Char>

i.ReservationNumber is of type String, ReservationNumbers is of type List<string>, c is of type IGrouping<Reservation, int>

What would be a way to force conversion to List<string> or how to make SelectMany to return a IEnumerable<string>

Upvotes: 0

Views: 854

Answers (1)

IMil
IMil

Reputation: 1400

If i.ReservationNumber is of type String, you need to write simply

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

SelectMany tries to iterate through the elements of ReservationNumber, which, being String, is an IEnumerable<char>

Upvotes: 3

Related Questions