Archive for June, 2009

LINQ: Selecting in Nested Collections

This took me longer than it should have to figure it out, so I am documenting it for later reuse. The case here is described as such:


I have a collection of person objects, which themselves contain a collection of address objects. I want to find all the addresses in a given city:





public class Address


{


     public string Street { get; set; }


     public string City { get; set; }


     public string Region { get; set; }


     public string Postal { get; set; }


     public AddressType Location { get; set; }


}


 


public class Person


{


     public string Name { get; set; }


     public string ID { get; set; }


     public string Title { get; set; }


     public List<Address> Addresses { get; set; }


}


….



IEnumerable<Address> results = from guy in allPersons


                               from addressResult in guy.Addresses


                               where addressResult City == “London”


                               select addressResult;


I understand this is similar to a join in a SQL statement, but in my case the data does not come from a database but a service where I can’t control data selection in that way.

Posted on:
Posted in .Net 3.5, Linq | Comments Off on LINQ: Selecting in Nested Collections