Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否在linq循环中获取上一个值?_C#_.net_Linq_C# 4.0 - Fatal编程技术网

C# 是否在linq循环中获取上一个值?

C# 是否在linq循环中获取上一个值?,c#,.net,linq,c#-4.0,C#,.net,Linq,C# 4.0,我正在尝试将下面的代码转换为简写linq,但不确定是否可行。使用Linq有没有更优雅的方法?出现的复杂情况是,拆分AllowedRole并检查每个角色是否为UserInRole是一个嵌套循环 bool allowed = RoleManager.IsUserUnrestricted(userId); if (!allowed) { foreach (var item in element.AllowedRoles.Split(',')) {

我正在尝试将下面的代码转换为简写linq,但不确定是否可行。使用Linq有没有更优雅的方法?出现的复杂情况是,拆分AllowedRole并检查每个角色是否为UserInRole是一个嵌套循环

   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);
    }
试试这个:

if (RoleManager.IsUserUnrestricted(userId)
||  element.AllowedRoles.Split(',')
           .Any(item => roleManager.IsUserInRole(userId, item.Trim()))) {
    ...
}
我们的想法是使用LINQ的
Any
函数来查找没有循环的第一个匹配项

if(RoleManager.IsUserUnrestricted(userId) || element.AllowedRoles.Split(',').Any(r=> roleManager.IsUserInRole(userId,r.Trim()))
{
        AddWidget(element.Name);
}

您可以使用以下内容:

element.AllowedRoles.Split(',').Any(r => roleManager.IsUserInRole(userId, r.Trim())) 

顺便说一句,我没有看到嵌套循环,您发布的代码中只有一个循环。你有元素的集合吗?还有,为什么你的问题的标题是“在linq循环中获取以前的值?”我看不出有任何必要这样做。

几乎相同的答案,你在1分钟内就找到了我:-)@MikeKulls我们很幸运Jon Skeet睡着了,他会比我们两个都领先三到四分钟:)