C#C
C#4y ago
Ossie

Index was out of range. How to check if list has items without triggering this error?

Hello, I have a list, with a list inside.
 List<List<dynamic>> characterData


This is because I wan't to have 3 possible lists, with a list inside. However there isn't always 3 lists present. Sometimes it might only be 1 or 2 lists that are filled, and the last one is empty. My problem occurs when trying to check if the List has any value. This works fine if none of the lists have any value, by checking if characterData.Count > 0. However when this is not the case, I try to check if a value inside the list is NullOrEmpty, however this is causin the error Index was out of range. Which makes sense because the list doesn't exist, but how would I then check if the list itself exists inside the the other list? I hope this makes any sense, I will post a snippet.

I would wanna check if characterData[i] exists, without getting an index error.

 List<List<dynamic>> characterData // This get its value from another place, not important

for (int i = 0; i <= 2; i++)
{
  if (characterData.Count > 0)
  {
    if (!string.IsNullOrEmpty(characterData[i][0].ToString())) // This give me a error, so how do I check if the list has any values, I'm just checking the first value as it seemed logically to me
    {
      // Rest of my code
    }
  }
}


Thanks,
Ossie
Was this page helpful?