即使列表为空,C# 列表计数也始终返回 1 [英] C# list count always returns 1 even when list is empty

查看:27
本文介绍了即使列表为空,C# 列表计数也始终返回 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 C# 调试一个方法,但我在这里似乎缺乏基本的语法技能!该方法接受日期列表作为逗号分隔的文本字符串.这个字符串被转换成一个列表,然后被处理.但是,似乎即使将空字符串传递给该方法,在对列表进行计数时仍然输出1.

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.

代码如下:

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;
    }

如果我传递一个空字符串作为 excludeDates 参数,它返回 1.如果我传递一个日期,它返回 1.如果我传递两个日期,它返回 2 等等.所以它有点工作,除了没有任何传递的地方在,当我期望它返回 0 但它实际上返回 1 时.

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?

谢谢

推荐答案

即使对于空字符串,Split 也会返回数组中的那个字符串,因此列表将使用...创建一个空字符串,生成一个 .Count 为 1. [编辑:您可以调用 excludeDates.Split(',', StringSplitOption.RemoveEmptyEntries) 这样它就不会.]

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.]

为了使您的函数按照您的预期运行,您可能应该尝试解析从 Split() 返回的每个日期"字符串,并且只增加有效日期的计数器.

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.

像这样:

    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;

如果您正在寻找最简单的方式,您应该只检查参数以查看它是否为空字符串,在这种情况下返回 0:

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;

这篇关于即使列表为空,C# 列表计数也始终返回 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆