Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# list count always returns 1 even when list is empty

Tags:

c#

list

count

I'm trying to debug a method in C# but my basic syntax skills here seem to be lacking! The method accepts a list of dates as a comma-separated text string. This string is converted to a list, then processed. However, it seems that even when an empty string is passed to the method, it still outputs 1 when the list is counted.

The code is as follows:

public static int DaysLeft(DateTime endDate, DateTime startDate, Boolean excludeWeekends, String excludeDates)
    {
        int counter = 0;

        List<string> excludeDatesList = new List<string>(excludeDates.Split(','));

        counter = excludeDatesList.Count;

        return counter;
    }

If I pass an empty string in as the excludeDates parameter, it returns 1. If I pass a single date it returns 1. If I pass two dates, it returns 2 etc. So it's kind of working except where there's nothing passed in, when I'd expect it to return 0 but it actually returns 1.

Can anyone point me in the right direction?

Thanks

like image 743
Dan Avatar asked Jul 20 '11 13:07

Dan


1 Answers

Even for an empty string, Split will return that string in the array, so the list will be created with... one empty string, producing a .Count of 1. [Edit: You can call excludeDates.Split(',', StringSplitOption.RemoveEmptyEntries) so that it doesn't.]

To make your function behave as you expect, you should probably try to parse each "date" string returned from Split(), and only increment the counter for valid dates.

Something like this:

    int counter = 0;
    var possibleDates = excludeDates.Split(',');

    foreach (var dateStr in possibleDates)
    {
        // Right now it just counts "good" dates, though could also do something
        //  with each date as well
        DateTime dt;
        if (DateTime.TryParse(dateStr, out dt))
            counter++;
    }

    return counter;

If you're looking for the simplest way, you should just check the parameter to see if it's the empty string, and return 0 in that case:

if (string.IsNullOrEmpty(excludeDates))
    return 0;
like image 191
dlev Avatar answered Oct 02 '22 18:10

dlev