Reputation: 572
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.
Upvotes: 0
Views: 533
Reputation: 2613
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;
}
}
Upvotes: 1
Reputation: 572
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.
Upvotes: 0