简体   繁体   中英

how to check List<string> is null

I wanna to check the values (its type is list) and if it is null, it starts again from at the beginning of the loop and if it is not, counter++. I mean if values is like: "values": [] the compile back at the beginning of loop.

I tried with if (id==null) and also I used this one (id.Contains("")) but the error happens. Error:Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index (Argument out of range exception was unhandled).

Data that I want to check (when the values is null)

{
  "cid": "241",
  "fnames": [
    "id",
    "name",
    "hash",
    "score",
    "rank"
  ],
  "values": [],
  "tal": 0,
  "sion": "v3"
}

Full data (when the values is not null)

{
  "cid": "64",
  "fnames": [
    "id",
    "name",
    "hash",
    "score",
    "rank"
  ],
  "values": [
    [
      "126",
      "126",
      "126",
      "1",
      "2.77"
    ],
      "tal": 0,
      "sion": "v3"
    }

Code

foreach (DataRow row in dt.Rows)
{
string url = "http://hgsfe/<uid>?groups=<uid>
var test = url.Replace("<uid>", Convert.ToString(row[uid]));
System.Diagnostics.Process.Start(test);
string client = (new WebClient()).DownloadString(test);
var pi = JsonConvert.DeserializeObject<read_json>(client);
List<string> id = pi.values[0];
if (id==null)         //also I used this one (id.Contains(""))   
continue;
if (id.Contains(Convert.ToString(row[tid])))
{
counter++;
}

尝试检查pi.Countpi.Length以获取列表中的项目数。

You have to check both:

 pi == null
 pi.values[0] == null

because you try the assignment, but pi doesn't event exist (probably)

When you debug your code, you can clearly see, where the application crashes.

Hope i could help you with that

Try the following

List<string> id = pi.values.ToList();

And after this just check the Count property of the list

if(id.Count<1)
    continue;
...
...

you did provide code with a lot of 'unknowns', but here is what could be wrong and you should check it to make your code safer:

  • what is uid ? You are accessing row[uid] . row is of type DataRow where accessing item which does not exist (specified by uid ) throws exception
  • what is pi ? what is pi.values ? Maybe you should check if pi is null, pi.values is null and you should definately check if pi.values contains any items (so if item values[0] is present). If its empty then values[0] will throw exception you mentioned.
  • pi.values[0] may be present, but it again may be assigned null. So your line if (id.Contains... may fail on that you are trying to call id.Contains on null item id . Check if its not null before call.
  • what is tid in row[tid] ? Again, check if such item is present in the row so you won't get DataRow exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM