How to check if list index exists in C #?

I have the following code snippet:

public static List<string> sqlData = new List<string>();

//
//  lots of code here
//

if (/* check here to see if the sqlData[whatever] index exists  */)
{
    sqlData.Insert(count2, sqlformatted);
}
else
{
    sqlData.Insert(count2, sqlformatted + sqlData[count2]);
}

I want to know how to check an index in sqlData to see if it exists before trying to insert something that contains.

+3
source share
3 answers

If this is always positive, you can use this:

if (whatever < sqlData.Count) { ... }

Or, if everything can be negative, you also need to add a test:

if (whatever >= 0 && whatever < sqlData.Count) { ... }
+6
source

Check the length by index:

sqlData.Count < count2
+3
source
if(sqlData.Count > whatever )
{
 //index "whatever" exists
  string str = sqlData[whatever];

}
+1
source

Source: https://habr.com/ru/post/1765173/


All Articles