Getting the Object From IGrouping in c#

2.5k Views Asked by At

I need to Access available Hotel Object From query2, here I am able to access HotelCode value using y.key, but How Can I Access the availableHotel Object from query2.

My Matrix MOdel

 public  class JsonMatrixModel
        {
            public class Result
            {

                public string responseId { get; set; }
                public string searchId { get; set; }
                public int totalFound { get; set; }
                public List<availableHotels> availableHotels { get; set; }
            }

            public class availableHotels
            {
                public string processId { get; set; }
                public string hotelCode { get; set; }
                public string availabilityStatus { get; set; }

                public double totalPrice { get; set; }
                public double totalTax { get; set; }

                public double totalSalePrice { get; set; }

                public string currency { get; set; }

                public string boardType { get; set; }
                public List<rooms> rooms { get; set; }



            }

            public class rooms
            {
                public string roomCategory { get; set; }
                public List<paxes> paxes { get; set; }
                public double totalRoomRate { get; set; }
                public List<ratesPerNight> ratesPerNight { get; set; }
            }

            public class paxes
            {
                public string paxType { get; set; }
                public int age { get; set; }


            }

            public class ratesPerNight
            {
                public string date { get; set; }
                public double amount { get; set; }
            }
        }

My Query

Enumerable<IGrouping<string, JsonMatrixModel.availableHotels>> quer2 =
      from ff in ddd
      from ss in ff.availableHotels.OrderBy(x =>x.totalSalePrice) group ss by ss.hotelCode;

Accessing the Value

  foreach (var y in quer2)
{  
  string ss = y.Key;
}
2

There are 2 best solutions below

2
On BEST ANSWER

After you make the grouping, make a projection to a new anonymous object with a property that will have the value of your key, and another could the the list of grouped values for that key.

var quer2 =
      from  ff in ddd
      from  ss in ff.availableHotels.OrderBy(x =>x.totalSalePrice) 
      group ss by ss.hotelCode
      select new
      {
        GroupKey = ss.Key,      
        GroupValuesList =  ss.ToList()
      };


Console.WriteLine(quer2.First().GroupKey);
0
On

IGroupping is just an IEnumerable with an additional Key property. is this what you want?

var groups = items.GroupBy(p => p.Property);
foreach (var group in groups)
{
    Console.WriteLine(group.Key);
    foreach (var item in group)
    {
        Console.WriteLine("\t{0}", item.AnotherProperty); 
    }
}