C#如何在foreach / for循环中添加数组的索引?

时间:2015-12-06 02:08:57

标签: c# arrays for-loop foreach int

C#newbie并且对于为什么这不起作用感到困惑。

假设我有一个{1,2,3}的数组。

如何循环遍历此数组以按设定增量更改值,例如,如果增量为1:

{1,2,3}变成{2,3,4}

如果它的2变为{3,4,5}等等。

这是我的尝试 -

foreach (int i in ls)
{
int index = i + increment;
}

2 个答案:

答案 0 :(得分:1)

你接近成功了,但是你失败了,因为你把增量的结果放到一个临时变量中,然后在每个循环中重置并且没有改变原始数组

而且foreach不适合这种操作,因为无论如何你需要一个索引来指向要编辑的正确的数组元素,所以for是更好的

int increment = 1;
for (int i = 0; i < ls.Length; i++) {
   int newValue = ls[i] + increment;
   ls[i] = newValue;
}

我创造了一个你可以测试的小提琴

https://dotnetfiddle.net/lkkLUv

请注意,我或多或少地尝试让你看到差异,但循环可以缩小到

for (int i = 0; i < ls.Length; i++) {
    ls[i] += increment;
}

答案 1 :(得分:-1)

使用您的符号,以下内容应该这样做:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
        if (UserService.IsLoggedIn())
        {
            model.IsLoggedIn = true;
            model.CurrentUser = UserService.GetCurrentUser();
            model.UserProfile = svc.GetByUserId(model.CurrentUser.Id);
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            var actionName = filterContext.ActionDescriptor.ActionName.ToLower();
            if (controllerName != "user" && actionName != "onboard" && model.UserProfile.OnboardStatus == 0)
            {
                HttpContext.Response.Redirect("/user/onboard/"+ model.UserProfile.Id);
                }
            }
}