How can I generate an Expression tree that queries an object with List<T> as a property?

Posted by David Robbins on Stack Overflow See other posts from Stack Overflow or by David Robbins
Published on 2010-04-20T17:39:51Z Indexed on 2010/04/20 18:03 UTC
Read the original article Hit count: 399

Forgive my clumsy explanation, but I have a class that contains a List:

public class Document
    {
        public int OwnerId { get; set; }
        public List<User> Users { get; set; }

        public Document() { }
    }

    public class User
    {
        public string UserName { get; set; }
        public string Department { get; set; }
    }

Currently I use PredicateBuilder to perform dynmica queries on my objects. How can I turn the following LINQ statement into an Expression Tree:

var predicate= PredicateBuilder.True<User>();
predicate= predicate.And<User>(user => user.Deparment == "HR"); 

var deptDocs = documents.AsQueryable()
          .Where(doc => doc.Users
          .AsQueryable().Count(predicate) > 0)
          .ToList();

In other words var deptDocs = documents.HasUserAttributes("Department", "HR").ToList();

© Stack Overflow or respective owner

Related posts about linq-to-objects

Related posts about c#