Ryan Ryan - 3 months ago 14
C# Question

How to use a HashSet in my LINQ query?

I have a query for all users that looks like this:

from
u in db.AspNetUsers
orderby
u.UserName
select
....


That works fine. But now I want to filter for a specific user role. There is a
u.AspNetRoles
that is a HashSet of objects. Each object has a
Name
property that is the name of the role.

So I only want to select users who have a role object with
Name
equal to
"SuperAdmin"
.

Previously I just tried to join on the tables with the role data but that didn't work because there is an AspNetUserRoles table that only has a UserID and a RoleID with no primary key. And supposedly it's not recommended to make an entity class for a table that doesn't have a primary key.

Answer

I think this does what you are asking:

from
    u in db.AspNetUsers
where
    u.AspNetRoles.Any(r => r.Name == "SuperAdmin")
orderby
    u.UserName
select
    . . .

The Any method will return true if any of the items in the collection meet the criterion lambda (r => r.Name == "SuperAdmin", in this case). If any items in the collection AspNetRoles of user object u has a Name where the value is "SuperAdmin", then the result of Any is true. If none of the items meet the criterion, the Any returns false.