2012-12-04 112 views
0
var objTypeIndex = from u in context.sistema_DocType_Index where u.docTypeId == id select u.indexId; 
indexIds = objTypeIndex.ToList(); 
int count = indexIds.Count(); 

string[] names = new string[] {}; 
int i = 0;      

foreach (int indexId in indexIds) 
{ 
    //resgata nome do indice e armazena em um array 
    string strIndiceID = indexId.ToString(); 
    int indiceID = Convert.ToInt32(strIndiceID); 
    var objIndexName = from u in context.sistema_Indexes where u.id == indiceID select u.idName; 
    name = 

    names[i] = objIndexName.First(); 

    i++; 
} 

此行以上的最後一個: 名稱[I] = objIndexName.First();System.IndexOutOfRangeException用於動態初始化數組

提供了以下錯誤:

System.IndexOutOfRangeException: Index was outside the bounds of the array. 

我知道這意味着什麼。我只是不容找出原因。

+0

你開始'字符串[] names'爲空數組,設置'INT I = 0',然後訪問'名字[我]' - 這是'名稱[0]' - 這是不存在的,因爲你的長度是0,而不是1. – zimdanen

+0

我刪除了MVC/ASP.NET標籤,因爲它們與問題無關。 –

+0

爲什麼你拿一個整數,將它轉換成一個字符串,然後將它解析回'foreach'循環內的一個int?只需使用'indexId'。 – Servy

回答

3

更換

string[] names = new string[] {}; 

通過

var names = new List<string>(); 

而不是

names[i] = objIndexName.First(); 

使用

names.Add(objIndexName.First()); 

然後,你就可以得到您的數組如下:

var nameArray = names.ToArray(); 
4

看看這裏:

string[] names = new string[] {}; 

您已經創建了一個陣列。您不能將任何元素放入該數組中。不存在i值此聲明將工作:

names[i] = objIndexName.First(); 

目前尚不清楚你想要做什麼,但也許你想要一個List<string>建立(與Add),而不是一個數組?或者,你也可能做這件事有一個單一的LINQ查詢...