Travis J
Travis J

Reputation: 82357

How can I sort a nested collection using linq?

I am fairly certain this is possible, but I am having some problems getting it to work. I am trying to get a simple object graph with only 1 level of nesting using linq. Here is an example of the structure:

public class City
{
 public int CityId { get; set; } 
 public string Name { get; set; }
 public List<House> Houses { get; set; }
}

public class House
{
 public int HouseId { get; set; }
 public int Number { get; set; }
 public int CityId { get; set; }
}

So what I am trying to do is get all the cities, with all of their related Houses. I am trying to have the cities sorted by Name, and then their nested houses sorted by number. I tried a projection, a foreach to sort, and a slow iteration after the query is complete. Here is the basics of what I have at the moment, but I cannot see how to access the nested set:

List<City> Cities = db.Cities.Include(c => c.Houses).OrderBy(c => c.Name).ToList();

How can I also manage to sort each cities Houses by their Number (without affecting the order that the cities are in)?

Upvotes: 2

Views: 2591

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149108

Try this

    var cities = (from city in db.Cities
                  orderby city.Name
                  select new {
                      City = city, 
                      Houses = city.Houses.OrderBy(c => c.Number)
                  })
                 .ToList();

Upvotes: -1

Abe Miessler
Abe Miessler

Reputation: 85126

Would something like this work?

var Cities = 
           (from c in db.Cities
           orderby c.Name
           select new
           {
               Name = c.Name,
               Houses = c.Houses.OrderBy(c => c.Number).ToList()
           }
          );

Upvotes: 4

Related Questions