2013-05-18 22 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();