-2

I would like to filter array of users, based on that if roles that exists in array are already contained in user roles list.

Here is my code which won't compile:

var roles = role.Split(','); // admin, basic, super-admin

listOfUsers = listOfUsers.Where(user => user.Roles.Contains(roles.Select(x => x)).ToList();

I want to do if admin and basic are contained in roles which is array of string to return only those users which have the same value in Roles array. (Roles is also list of strings) but this reproduces an error:

enter image description here

6
  • 1
    can you add more code? what's the type of listOfUsers, etc? what type is user.Roles? Commented Sep 1, 2020 at 21:21
  • Are you looking for users that have ALL roles specified in roles, or users that have ANY role in roles? Commented Sep 1, 2020 at 21:22
  • @DavidFox It states that Roles is also a List<string> Commented Sep 1, 2020 at 21:23
  • @RufusL For users that have any roles specified in roles.. Yes Roles is also a List<string> Commented Sep 1, 2020 at 21:23
  • 2
    Assuming that user.Roles is an IEnumerable<string>, then user.Roles.Contains(roles.Select(x => x)) expects a string as a parameter. We know that roles is a string[] (assuming that role is a string containing stuff separated by commas). Then, roles.Select(x=>x) is an IEnumerable<string> not the string the function expects. This would be much easier if you gave us more code (as suggested by @DavidFox) and if your variable names weren't role, roles and Roles Commented Sep 1, 2020 at 21:28

1 Answer 1

2

To find a match in one list of strings from another, you can check if Any user roles are contained in the roles list:

listOfUsers = listOfUsers.Where(user => user.Roles.Any(roles.Contains)).ToList();

If you want to do a case-insensitive comparison, you can pass a comparer to the Contains method:

listOfUsers = listOfUsers
    .Where(user => 
        user.Roles.Any(role => roles.Contains(role, StringComparer.OrdinalIgnoreCase)))
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.