![](/img/trans.png)
[英]System.IndexOutOfRangeException on the collection which initialized once and length not changing, how?
[英]System.IndexOutOfRangeException for a dynamic initialized array
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++;
}
最后一行以上的行:names [i] = objIndexName.First();
給出以下錯誤:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
我知道那是什么意思。.我只是不知道為什么。
看這里:
string[] names = new string[] {};
您創建了一個空數組。 您不能將任何元素放入該數組。 此語句i
用於i
值:
names[i] = objIndexName.First();
目前尚不清楚您要做什么,但是也許您想建立一個List<string>
(使用Add
)而不是一個數組? 或者您可能只用一個LINQ查詢就可以完成整個工作...
更換
string[] names = new string[] {};
通過
var names = new List<string>();
而不是
names[i] = objIndexName.First();
采用
names.Add(objIndexName.First());
然后,您將可以按照以下方式獲取數組:
var nameArray = names.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.