
I have a keyValupair of Hotel details:
//This is where the data comes from : -
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
dynamic hotels1 = (dynamic)json_serializer.DeserializeObject(jso);
var keyValuePairs = hotels1["hotels"];
var hotelList = keyValuePairs["hotels"];   // hotelList[0]  ={'key'='Code' ;value='123'} 
                                           //{'key'='Name' 
                                           // ;value='Sheraton'}  
how do I convert this to a list of Hotel
List<Hotel> hotaals = new List<Hotel>();
where Hotel is
public class Hotel {
    public int code { get; set; }
    public string name { get; set; }
}
I use a for loop to map fields, but my great boss says it's inefficient and I have to use Linq.
The loop I use
foreach (dynamic h in hotelList) {
   oneHotel = new Hotel();
   oneHotel.code = h["code"];
   oneHotel.name = h["name"];
   myHotels.Add(oneHotel);
}
Well the brute force way would be to just project the dictionary to objects by hard-coding the properties:
List<Hotel> hotaals = hotelList.Select(kvp => new Hotel {
                                    code = kvp['Code'],
                                    name = kvp["Name"]
                                    })
                               .ToList();
I would also challenge what your "great boss" means by inefficient".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With