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++;
}

This line above the last: names[i] = objIndexName.First();

gives the following error:

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

I know what that means.. I just can´t figure out why.

3
  • You're initiating string[] names as an empty array, setting int i = 0, then accessing names[i] - which is names[0] - which doesn't exist, since your length is 0, not 1. Commented Dec 4, 2012 at 19:24
  • I've removed the MVC/ASP.NET tags as they're irrelevant to the problem. Commented Dec 4, 2012 at 19:24
  • Why do you take an integer, convert it to a string, and then parse it right back into an int inside of the foreach loop? Just use indexId instead. Commented Dec 4, 2012 at 19:31

2 Answers 2

4

Look here:

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

You've created an empty array. You can't put any element into that array. There is no value of i for which this statement will work:

names[i] = objIndexName.First();

It's not clear what you're trying to do, but perhaps you want a List<string> to build up (with Add) rather than an array? Or you could probably do the whole thing with a single LINQ query...

Sign up to request clarification or add additional context in comments.

Comments

3

Replace

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

By

var names = new List<string>();

And instead of

names[i] = objIndexName.First();

Use

names.Add(objIndexName.First());

Then, you will be able to get your array as follow:

var nameArray = names.ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.