0

I have a Array.It has for example 10 rows. I need to checka flg. if flag has value false it goes to array number one,if it have flag true it goes go array number 2.I'm trying something like this.

if (lista2[i].FLG_FALHA == true)
{
    listaInc[c] = lista2[i];
    i++;
    c++;
}
else
{
    listaAlr[o] = lista2[i];
    o++;
    i++;
}

This is where i declare the arrays.

 List<AcompanhamentoSiltIncDTO> lista2 = new List<AcompanhamentoSiltIncDTO>();
 List<AcompanhamentoSiltIncDTO> listaInc = new List<AcompanhamentoSiltIncDTO>();
 List<AcompanhamentoSiltIncDTO> listaAlr = new List<AcompanhamentoSiltIncDTO>();

I get this error,it's like the arrays are not initialized.

"{"The index was out of range, it should be non-negative and less than the size of the collection. \ R \ nName parameter: index"}"

4
  • 1
    Those are not arrays but Lists. Use the Add() method. Commented Mar 9, 2017 at 20:41
  • 1
    Also, you are adding to the same List in both the then and else branches. An error you would probably not have made with some better naming of your variables. Commented Mar 9, 2017 at 20:42
  • When you get an error telling you an index needs to be less than the size of the collection, check two things: The value of the index, and the size of the collection. At least one of them is not what you think it is. Commented Mar 9, 2017 at 20:43
  • I 'ill try,its two list i trype wrong,i will correct above. Commented Mar 9, 2017 at 20:44

3 Answers 3

2

You should call the Add() method of your list:

if (lista2[i].FLG_FALHA == true)
  listaInc.Add(lista2[i]);
else
  listaAlr.Add(lista2[i]);

Otherwise, since your listaAlr and listaInc have no element, you get cannot access element at position o : listaInc[o]

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

Comments

0

You get this error because you got out of range of your array. Check out your indexes. But for this task I suggest you working with linq. It gives you a lot of good functionality.

And if you have "List<>" you need to add elements to this list with "Add" method. So code will be the next:

if (lista2[i].FLG_FALHA == true)
{
    listaInc.Add(lista2[i]);
    i++;
}
else
{
    listaAlr.Add(lista2[i]);
    i++;
}

But as I said you may use LinQ. Code will be the next:

listInc = lista2.Where(x => x.FLG_FALHA);
listAlr = lista2.Where(x => !x.FLG_FALHA);

Comments

0

You can solve this with LINQ.

var listaInc = from n in lista2
                where n == true
                select n;

var listaAlr = from n in lista2
                where n == false
                select n;

Bits more, bits less, but that is what I would do.

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.