Search code examples
c#asp.net-mvclinqigrouping

Getting the Object From IGrouping in c#


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;
}

Solution

  • 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);