C# 递增变量上的越界异常

C# 递增变量上的越界异常,c#,C#,我已经离开了C和MVC。我真的在与下面的错误作斗争,我真的没有看到它。我有一个限制列表,我想将它们的键添加到字符串[] int cntr = 0; //loop through restrictions and add to array foreach (var Restriction in this.admingroupRepository.Context.AdminRestrictions.ToList()) { currentRestrictionKeys[cntr] = Rest

我已经离开了C和MVC。我真的在与下面的错误作斗争,我真的没有看到它。我有一个限制列表,我想将它们的键添加到字符串[]

int cntr = 0;
//loop through restrictions and add to array
foreach (var Restriction in this.admingroupRepository.Context.AdminRestrictions.ToList())
{
    currentRestrictionKeys[cntr] = Restriction.Key;
    cntr += 1;
}
这是我在cntr+=1行上得到的错误:

Index was outside the bounds of the array.

我不明白这是从哪里来的,foreach会在cntr超出数组边界之前中断,对吗?

您为
currentRestrictionKeys
分配的空间太少。但是你根本不需要预先分配它;您只需对LINQ使用一个简单的投影:

var currentRestrictionKeys = this.admingroupRepository.Context.AdminRestrictions
                                 .Select(r => r.Key)
                                 .ToArray();

currentRestrictionKeys
的类型是什么?如何声明您的
currentRestrictionKeys
变量?string[]让我更新初始帖子,对不起。因为你们问了这些问题,我意识到我做错了什么。我不敢相信我被这么简单的事情难倒了……每个人都会遇到;)