如何检查C#中是否存在列表索引?
我有以下代码片段:如何检查C#中是否存在列表索引?,c#,list,C#,List,我有以下代码片段: 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(c
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]);
}
publicstaticlist sqlData=newlist();
//
//这里有很多代码
//
if(/*检查此处是否存在sqlData[where]索引*/)
{
Insert(count2,sqlformatted);
}
其他的
{
Insert(count2,sqlformatted+sqlData[count2]);
}
我想知道的是,在尝试插入包含自身的内容之前,如何检查sqlData上的索引以查看它是否存在。如果任何内容始终为正,则可以使用以下方法:
if (whatever < sqlData.Count) { ... }
if(无论什么
或者,如果任何东西也可能是阴性的,那么您也需要添加一个测试:
if (whatever >= 0 && whatever < sqlData.Count) { ... }
if(whatever>=0&&whatever
对照索引检查长度:
sqlData.Count < count2
sqlData.Count
我认为你的问题措词不当,你得到的各种不同答案表明人们对它的理解不同。请举例说明您想要什么。如果可能的话,请坚持使用foreach(sqlData中的var-sqlString)让我发布整个代码部分。我更新了上面的代码,以便为您提供更全面的信息。@Mark:我不是最擅长提出关于C#的问题的人,因为我对这门语言非常陌生。最近,我退出了PHP潮流,加入了this one=p当我使用sqlData.Length时,Visual C#Express 2010没有提供它作为选项。@Claude:很抱歉,这是一个错误。它是列表的计数(数组的长度)。我已经更新了我的答案。@Abe Miessler:我想应该没问题。如果列表长度为1,则0是最大的有效索引。@Abe:
if(sqlData.Count > whatever )
{
//index "whatever" exists
string str = sqlData[whatever];
}