即使列表为空,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;