Intersection. Is this possible? RRS feed

  • Question

  • Hello,

    I have an entity as follows:

      public class User {
        public Int32 Id { get; set; }
        public virtual ICollection<Role> Roles { get; set; }
      } // User

    The Role entity as a property NAME. I have the following string array:

    String[] filterRoles = { "role2", "role4 };

    I need to select all users where in their Roles Names there is at least of the filterRoles.

    Basically, if the intersection of one a user.Roles.Select(x => x.Name).ToArray() and filterRoles is not empty then the user is picked.

    Of course, I would like this selection to take place on the database and not load all items in memory.

    How can I do this?

    Thank You,


    Friday, July 13, 2012 6:21 PM


  • Hi Miguel;

    The following code snippet will select all users who has a role in the filterRoles array.

    String[] filterRoles = { "role2", "role4" };
    var results = from u in DbContextInstance.User
                  where u.Role.Any( r => filterRoles.Contains( r.NAME ))
                  select u;


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Friday, July 13, 2012 7:08 PM