LINQ to NHibernate expressions on List<>

1.7k Views Asked by At

I'm using LINQ to NHibernate, and have a model that looks something like this (simplified):

public class Person {
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address {
    public virtual string Street { get; set; }
    public virtual string City { get; set; }
}

I can perform the following LINQ to NHib query:

Expression<Func<Person, bool>> predicate = pr => pr.FirstName == "Bob";
List<Person> people = session.Query().Where(predicate).ToList();

But I'm stuck trying to return all the people who have an address with City == "Something".

1

There are 1 best solutions below

1
On BEST ANSWER

How about:

List<Person> people = session.Query()
                        .Where(p => p.Addresses.Any(a => a.City == "Something"))
                        .ToList();

That's assuming you want the query to still be performed in the database. If you just want to do it within the List<Person> already returned:

people = people.Where(p => p.Addresses.Any(a => a.City == "Something"))
               .ToList();