2013-05-18 20 views
-2

我一直在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超出数组边界的对?

+0

什么是'currentRestrictionKeys'类型? –

+0

你如何声明你的'currentRestrictionKeys'变量? – ppetrov

+0

string []让我更新我的初始文章,对不起。 – Chris

回答

2

您为currentRestrictionKeys分配的空间太小。但你根本不需要预先分配它;你可以使用一个简单的投影与LINQ:

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