Linq > Contains

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I need to select all users which User.Roles contain a role with Id =
RoleId:

return _context.Users.Select(u => new Models.User {
Approved = u.Approved,
// ...
}).Where(u => u.Roles.Contains(r => r.Id == RoleId)).AsQueryable
();

I get an error on Contains as follows:
Cannot convert lambda expression to type 'Domain.Models.Role' because
it is not a delegate type

I don't have the entire role, Id and Name, I have only its Id (RoleId)

I use the following that compiles:
}).Where(u => u.Roles.Count(r => r.Id == RoleId) > 0).AsQueryable();

But I am not sure if this is the way to do it ...

How should I implement this.

Thanks,
Miguel
 
Hello,

I need to select all users which User.Roles contain a role with Id =
RoleId:

return _context.Users.Select(u => new Models.User {
Approved = u.Approved,
// ...
}).Where(u => u.Roles.Contains(r => r.Id == RoleId)).AsQueryable
();

I get an error on Contains as follows:
Cannot convert lambda expression to type 'Domain.Models.Role' because
it is not a delegate type

The error is telling you that the type 'Domain.Models.Role" is not a
delegate type, and so the lambda expression "r => r.Id == RoleId" is not
convertable to 'Domain.Models.Role".

Based on the example, I would guess that you actually should be calling
the Enumerable.Any() method instead of Enumerable.Contains(). The
Contains() method tells you if a specific element is present in a
collection. The Any() method tells you if any element meets a specific
condition. The difference is subtle, but very important.
I don't have the entire role, Id and Name, I have only its Id (RoleId)

I use the following that compiles:
}).Where(u => u.Roles.Count(r => r.Id == RoleId) > 0).AsQueryable();

But I am not sure if this is the way to do it ...

It's a way to do it. It's not quite as efficient as calling Any() would
be, but it wouldn't have been the end of the world if that was how you
needed to do it. Of course, another option would have just been to write
an explicit loop that just sets a flag and terminates the first element it
finds that meets the condition.

But fortunately, there is the Any() method. Just call that. It should be
fine.

Pete
 
But fortunately, there is the Any() method.  Just call that.  It should be  
fine.

And unfortunately I always forgot about Any() and end up going around
around with Contains, etc ...

I just created a big Post It with "Any()!!!"

Thank You Pete,
Miguel
 
Back
Top