Linq query

S

shapper

Hello,

I have the following list:

IList<Int32> roles = { 1, 2, 3 }

I need to get all users where in user.Roles there is at least one Role
which is id 1, 2 OR 3.
var a = users.Where(u => u.Roles. ??? );

How can I do this?

Thanks,
Miguel
 
M

Martin Honnen

shapper said:
I have the following list:

IList<Int32> roles = { 1, 2, 3 }

I need to get all users where in user.Roles there is at least one Role
which is id 1, 2 OR 3.
var a = users.Where(u => u.Roles. ??? );

users.Where(u => u.Roles.Any(r => roles.Contains(r)))
assuming u.Roles is IEnumerable<int>. If it is an object with an id
property of type int then maybe
users.Where(u => u.Roles.Any(r => roles.Contains(r.id)))
 
S

shapper

   users.Where(u => u.Roles.Any(r => roles.Contains(r)))
assuming u.Roles is IEnumerable<int>. If it is an object with an id
property of type int then maybe
   users.Where(u => u.Roles.Any(r => roles.Contains(r.id)))

This is a little bit confusing and I keep having some errors... I
tried the following:

var a = users.Where(u => u.Roles.Any(r => r.Id == 1));

Basically I am trying to get all users that have a Role with Id = 1.

And I get the error:
base {System.SystemException} = {"Member access 'Int32 Id' of 'Role'
not legal on type 'System.Collections.Generic.IList`1[Role]."}

Any idea ... It compiles but then I get this error.

Thanks,
Miguel

And I get
 
S

shapper

   users.Where(u => u.Roles.Any(r => roles.Contains(r)))
assuming u.Roles is IEnumerable<int>. If it is an object with an id
property of type int then maybe
   users.Where(u => u.Roles.Any(r => roles.Contains(r.id)))

        Martin Honnen --- MVP Data Platform Development
       http://msmvps.com/blogs/martin_honnen/

This is a little bit confusing and I keep having some errors... I
tried the following:

var a = users.Where(u => u.Roles.Any(r => r.Id == 1));

Basically I am trying to get all users that have a Role with Id = 1.

And I get the error:
base {System.SystemException} = {"Member access 'Int32 Id' of 'Role'
not legal on type 'System.Collections.Generic.IList`1[Role]."}

Any idea ... It compiles but then I get this error.

Thanks,
Miguel

And I get

I solved it ... My problem was that u.Roles was returning null.

Thank You,
Miguel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

List to EntityCollection 0
Intersection of Lists 5
Generics 7
Linq > Contains 2
List<String> 15
List. Add, Remove. 1
Sub select in LINQ 1
Add item at start 5

Top