Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous value in linq loop?

Tags:

c#

.net

linq

c#-4.0

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);
    }
like image 801
TruMan1 Avatar asked Feb 18 '26 18:02

TruMan1


1 Answers

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.

like image 180
Sergey Kalinichenko Avatar answered Feb 21 '26 08:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!