Enumerable method to query a object model and find a field value

Viewed 47

I have 2 object models here is the first and second.

Inventory

    public int Inventory_ID { get; set; }
    public string ResType { get; set; }
    public string RoomType { get; set; }
    public DateTime? Date_Inventory { get; set; }
    public string CalledInPort { get; set; }
    public string HotelName { get; set; }
    public string HotelAddres { get; set; }

Inventory_Info

    public int Inventory_ID { get; set; }
    public DateTime? Inventory_Date { get; set; }
    public int Hotel_ID { get; set; }
    public int Total_Rooms_Available { get; set; }
    public string HotelName { get; set; }
    public string Hotel_Addr1 { get; set; }
    public string Hotel_City { get; set; }
    public string Hotel_State { get; set; }
    public string Hotel_Zip { get; set; }

I loaded each model with data from tables. The inventory model HotelName field is null at this point, but both share inventory_ID is there a enumerable method to query inventory_info model by the inventory ID and find the hotelname set it to the null field in Inventory model?

There var 'output' is inventory model, var 'InventoryInfo' is where the hotel name information is at.

I have tried this so far but not sure where to go , any help would be appreciated. Thank you.

        foreach (var item in output)
        {
            //set name 
            item.HotelName = InventoryInfo.Where(u => u.Inventory_ID == item.Inventory_ID)//find name?
            //set address
            //item.HotelAddres=
        }
1 Answers

This assumes the Inventory_ID is ALWAYS in BOTH tables.

item.HotelName = InventoryInfo.First(u => u.Inventory_ID == item.Inventory_ID).HotelName

If the Inventoy_ID is not guaranteed to be in the info table then you can do something like:

foreach (var item in output)
{
  var info = InventoryInfo.FirstOrDefault(u => u.Inventory_ID == item.Inventory_ID)
  if (info != null)
    item.HotelName = info.HotelName;
}

and decide what to do if anything if a hotel name cannot be found.

Related