简体   繁体   English

C# 即使列表为空,列表计数也始终返回 1

[英]C# list count always returns 1 even when list is empty

I'm trying to debug a method in C# but my basic syntax skills here seem to be lacking.我正在尝试调试 C# 中的方法,但我这里的基本语法技能似乎缺乏。 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.计算列表时它仍然输出 1。

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.如果我传递一个空字符串作为 excludeDates 参数,它返回 1。如果我传递一个日期,它返回 1。如果我传递两个日期,它返回 2 等等。所以它有点工作,除了没有传入任何东西,当我希望它返回 0,但它实际上返回 1。

Can anyone point me in the right direction?谁能指出我正确的方向?

Thanks谢谢

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也会在数组中返回该字符串,因此将使用...创建一个空字符串,生成.Count 1。 [编辑:您可以调用excludeDates.Split(',', StringSplitOption.RemoveEmptyEntries)以便它不会。]

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.为了使您的 function 行为符合您的预期,您可能应该尝试解析从Split()返回的每个“日期”字符串,并且只增加有效日期的计数器。

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:如果您正在寻找最简单的方法,您应该只检查参数以查看它是否为空字符串,并在这种情况下返回 0:

if (string.IsNullOrEmpty(excludeDates))
    return 0;

Splitting on the character is returning an empty element.拆分字符将返回一个空元素。

Try using excludeDates.Split(',', StringSplitOptions.RemoveEmptyEntries) instead.尝试使用excludeDates.Split(',', StringSplitOptions.RemoveEmptyEntries)代替。

You can use the remove empty entries option.您可以使用删除空条目选项。

var blah = "";

var split = blah.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries);
var split2 = blah.Split(new[]{';'});

// Returns zero
Console.WriteLine(split.Length);

// Returns one
Console.WriteLine(split2.Length);

That is normal behavior.那是正常的行为。 When there is nothing to split it will return a list with the string itself as the first element which counts as one.当没有要拆分的内容时,它将返回一个列表,其中字符串本身作为第一个元素,计为一个。

The array returned by String.Split() always has one element in it, even if it is the empty string. String.Split() 返回的数组总是有一个元素,即使它是空字符串。

Inserting an empty string into the list will create a list of one element.在列表中插入一个空字符串将创建一个包含一个元素的列表。 That element would be your empty string.该元素将是您的空字符串。

The result of calling string.Split on a string that doesn't contain the delimiter (in this case, a comma), is an array containing a single element, namely the original string.对不包含分隔符(在本例中为逗号)的字符串调用string.Split的结果是包含单个元素的数组,即原始字符串。 This also happens if the string is empty.如果字符串为空,也会发生这种情况。

The solution is to specify Split to omit empty entries:解决方案是指定Split以省略空条目:

List<string> excluseDatesList = new List<string>(excludeDates.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

As dlev said.. but to add an example to illustrate, if you pass in the string "," - which is just a comma, then ",".Split(',').Count() will return 2. for ",,,," which is just four commas, you will get back 5 for the count...正如dlev所说..但添加一个例子来说明,如果你传入字符串"," - 这只是一个逗号,那么",".Split(',').Count()将返回2。对于",,,,"这只是四个逗号,你会得到 5 的计数......

if you look at the Split method, it has the following logic:如果您查看 Split 方法,它具有以下逻辑:

int num = this.MakeSeparatorList(separator, ref sepList);
if (num == 0 || count == 1)
{
    return new string[]
    {
        this
    };
}

Therefore, even if the string is an empty string it will return a single item in the array.因此,即使字符串是空字符串,它也会返回数组中的单个项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM