I am trying to convert the code below to a shorthand linq, but not sure if it is possible. Is there a more elegant way to do this using Linq? The complication occurs is that it is a nested loop to split the AllowedRoles and checking each one if it IsUserInRole.
bool allowed = RoleManager.IsUserUnrestricted(userId);
if (!allowed)
{
foreach (var item in element.AllowedRoles.Split(','))
{
if (roleManager.IsUserInRole(userId, item.Trim()))
{
allowed = true;
break;
}
}
}
if (allowed)
{
AddWidget(element.Name);
}
Try this:
if (RoleManager.IsUserUnrestricted(userId)
|| element.AllowedRoles.Split(',')
.Any(item => roleManager.IsUserInRole(userId, item.Trim()))) {
...
}
The idea is to use LINQ's Any function to find the first matching item without a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With