Group list and subgroup

I am using the following class

class Country
{
   int CtryID {get; set;}
   List<City> city {get; set;}
}

class City
{
   string county {get; set;}    
   int sqkm {get; set;}
}

      

CtryID has values ​​like 1,2,3, and county has values ​​like "County 1", "County 2", etc.

I want to get a result like this

1
   County 1
   County 6
   County 3
2   
   County 9
   County 4
   County 2

      

How can I achieve this with a Lambda query?

This is what I used. The list is called ListA

 var lst = from aa in ListA
                    from cny in aa.ctryid
                    select new
                    {
                        CountryID= aa.CtryID,
                        CountyName= cny.County
                    };

      

Query 2: Also in my second query (separate from the first one) I want to order a country and then every City within the country without repeating the country multiple times for every City?

+2


a source to share


1 answer


var countryGroups = (from aa in ListA
                    from cny in aa.ctryid
                    select new
                    {
                        CountryID= aa.CtryID,
                        CountyName= cny.County
                    }).GroupBy(n => n.CountryID);

      

This will group your results with a CountryID

, but the output will not be a list - they will be groupings.



To output, iterate over countryGroups

, and in each of them iterate over objects CountyName

.

0


a source







All Articles