Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert key value pair to a custom object list

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);
}
like image 746
Jayapen Jose Avatar asked Oct 29 '25 00:10

Jayapen Jose


1 Answers

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".

like image 180
D Stanley Avatar answered Oct 30 '25 17:10

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!