简体   繁体   中英

Counting in lists with conditional statements

I know this is a common topic but I have been through most of the threads here on Stackoverflow and having followed them, can't see to get mine to satisfy all conditions.

I want to return the 2nd item in a list and if the list is null or only has 1 item in it, return 0;

I have this:

public int practice(List<int> items)
{
if (items == null)
    {
      return 0;
    }
else if (items.Count == 1)
    {
      return 0;
    }
else
   {
     int second_place = items[1];
     return second_place;
   }
}

I can't get this to work if the list has only 1 item in it. It just bypasses my else if condition and then fails. I have tried items.Count and items.Count() but it doesn't seem to make a difference.

Instead of adding another else condition, you could just combine them as follows:

 public int practice(List<int> items)
    {
        if (items == null || items.Count <= 1)
        {
            return 0;
        }
        else
        {
            int second_place = items[1];
            return second_place;
        }
    }

Ok so I figured out what I wasn't doing correct. The code wasn't passing if the list had 0 items in it (but was not null).

So I added another else if statement to handle that:

else if (items.Count == 0)
{
return 0;
}

And then it passed. I didn't originally do this because I had not initially thought of the case where the list is not null but has 0 items in it. I was incorrectly thinking it had either a value of null or 1 item or greater.

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