tags:

views:

41

answers:

2

I am using the following class

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

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

I want to order the result like this

Here's is some sample data for Country and City

Country

US
UK
Canada

City

CityC
CityF
CityA
CityB
CityG
CityD
CityE

I want to order the records by Country and then City (assuming some cities belong to respectivce countries) and print them like this

Canada CityA CityB CityE

UK CityG CityF

US CityC CityD

and so on

+1  A: 

It depends a lot on the technology you use how to display this. For instance, are you using a ASP.NET web site, Windows Forms or Console Application. Are you using a O/RM tool or in-memory collection. Here is an example using in-memory objects, with LINQ, in a Console Application:

IEnumerable<Country> countries = GetCountries();

foreach (var country in countries.OrderBy(c => c.Name))
{
    Console.Write(country.Name + " ");

    foreach (var city in country.Cities.OrderBy(c => c.Name))
    {
        Console.Write(city.Name + " ");
    }

    Console.WriteLine();
}

Please note that I changed your object model for this. A gave Country a Name property, gave City a Name property and renamed the city property to Cities.


You can also do this:

var countriesNames =
    from country in countries
    order by country.Name
    let cityNames = country.Cities.OrderBy(c => c.Name).ToArray()
    select new
    {
        Name = country.Name
        Cities = string.Join(" ", cityNames)
    }

foreach (var country in countriesNames)
{
    Console.WriteLine(country.Name + " " + country.Cities);
}
Steven
Ok any way to avoid foreach loop in LINQ? and write it like -- from Co in countriesfrom ci in Co.Cityorderby Co.CtryID, ci.county
Gokul
I updated the answer and added a new example that shows a solution without the inner `foreach`.
Steven
A: 

I don't like your class structure and what John Skeet said in the comment is true. You should listen to him. He has a big reputation. :)

At the very least you should change to the following:

class Country
{
   string CtryID {get; set;}
   List<City> cities {get; set;}
}

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

}

Populate as you said in your comment (but change this to a database or xml file some time):

List<Country> countries = new List<Country> { new Country() { CtryID = "US", cities = new List<City> { new City() { CityID  ="CityF", sqkm = 2803 },...etc

Then, when you have a populated object graph do the following to get your output:

countries.ForEach(ctry => {
     Console.Write(ctry.Name + " ");
     foreach (var city in ctry.cities)
     {
         Console.Write(city.Name + " ");
     }
     Console.WriteLine("");
});
Daniel Dyson