tags:

views:

21

answers:

2

I have an array of Person pocos, populated below. I'm trying display them alphabetically by Province, then by LastName within the Province. I'm using grouping and I can get the Provinces sorted fine, just not sure how to order the people within the province group.

This code:

Person[] people = new Person[]
{
    new Person() { FirstName = "Tony", LastName = "Montana", Age = 39, HomeProvince = "Ontario" },
    new Person() { FirstName = "Bill", LastName = "Smith", Age = 23, HomeProvince = "Ontario" },
    new Person() { FirstName = "Jane", LastName = "Doe", Age = 23, HomeProvince = "Alberta" },
    new Person() { FirstName = "John", LastName = "Doe", Age = 23, HomeProvince = "Alberta" },
    new Person() { FirstName = "Alex", LastName = "DeLarge", Age = 19, HomeProvince = "British Columbia" },
    new Person() { FirstName = "Travis", LastName = "Bickle", Age = 42, HomeProvince = "Quebec" },
    new Person() { FirstName = "Ferris", LastName = "Beuller", Age = 17, HomeProvince = "Manitoba" },
    new Person() { FirstName = "Maggie", LastName = "May", Age = 23, HomeProvince = "Ontario" },
    new Person() { FirstName = "Mickey", LastName = "Mouse", Age = 93, HomeProvince = "Alberta" },
    new Person() { FirstName = "Frank", LastName = "Darabont", Age = 49, HomeProvince = "Ontario" }
};

var query =
    from person in people
    group person by person.HomeProvince into g
    orderby g.Key
    select new { Province = g.Key, People = g };

foreach (var prov in query)
{
    Console.WriteLine("{0}: ", prov.Province);
    foreach (var person in prov.People)
    {
        Console.WriteLine("  {0} {1}, {2}", person.FirstName, person.LastName, person.Age);
    }
}

Gives me this output:

Alberta:
  Jane Doe, 23
  John Doe, 23
  Mickey Mouse, 93
British Columbia:
  Alex DeLarge, 19
Manitoba:
  Ferris Beuller, 17
Ontario:
  Tony Montana, 39
  Bill Smith, 23
  Maggie May, 23
  Frank Darabont, 49
Quebec:
  Travis Bickle, 42

As you can see, the Provinces are listed alphabetically but how do I list the people within the province (i.e for Ontario I want this order: Darabont, Montana, May, Smith).

+2  A: 

Assuming that you want alphabetical order by LastName then change this:

select new { Province = g.Key, People = g };

to:

select new { Province = g.Key, People = g.OrderBy(p => p.LastName) };

But note that your example "Darabont, Montana, May, Smith" is not quite in alphabetical order. I assume that this was just a mistake on your part, but if this is actually the order you want, please explain the rule you are using to generate this ordering.

Mark Byers
Damn that was fast! I want to mark it as 'Accepted Answer' but the system won't let me do that for another 8 minutes. :)
eponymous23
A: 

should be able to, after the select statement, to orderby(person => person.LastName);

Gnostus