Reputation: 8477
I have a string array and another object that has a list of objects, on of the properties is a string.
public string[] allowedroles;
foreach (var role in allowedroles)
{
if (user.RolesList.Exists(r => r.Name == role))
{
authorize = true;
break; // if one match that break out of loop
}
}
Is there a way to perform with just a LINQ statement, without the foreach loop?
Upvotes: 1
Views: 98
Reputation: 1499790
It sounds like you want:
var authorize = user.RolesList.Exists(r => allowedRoles.Contains(r.Name));
Or transform the list of roles into their names, and see whether that intersects with the allowed roles:
var authorize = user.RolesList.Select(r => r.Name).Intersect(allowedRoles).Any();
Note that you could use Any
instead of Exists
, which would stop it being specific to List<T>
:
var authorize = user.RolesList.Any(r => allowedRoles.Contains(r.Name));
Also note that even though the foreach
loop is no longer in the code, using LINQ won't make this code any faster - there's still a loop, it's just in the LINQ code rather than in your code. But hey, readability is still a big win :)
Upvotes: 3