简体   繁体   English

IF 语句检查 null 或 String.Empty

[英]IF statement checking for null or String.Empty

So I have a list with some data in it such as an input path, output path as well as column headings.所以我有一个列表,其中包含一些数据,例如输入路径、output 路径以及列标题。 As can been seen there are six column headings however some may be null as they do not have to be used.可以看出有六个列标题,但有些可能是 null,因为它们不必使用。 Because of this I created a method to filter the data so that only useful data remains.因此,我创建了一种过滤数据的方法,以便只保留有用的数据。

List<string> data = new List<string> { "C:/", "C:/Documents", "Hello", Goodbye". null, null, null, null } // Data to be passed into method
List<string> filteredData = new List<string>();

public void FilterData(List<string> data)
{
   foreach (var d in data)
   {
      if (d != null || d != String.Empty)
      {
         filteredData.Add(d);
      }
   }
}

Why is it that when I pass the List data into this method none of the data is filtered so that filteredData will contains the same as data , but when I use the following (if statement only evaluates if not null) it filters correctly?为什么当我将 List data传递给此方法时,没有任何数据被过滤,因此filteredData将包含与data相同的内容,但是当我使用以下内容时(如果语句仅评估非空),它会正确过滤?

public void FilterData(List<string> data)
    {
       foreach (var d in data)
       {
          if (d != null)
          {
             filteredData.Add(d);
          }
       }
    }

Thanks谢谢

You:你:

if (d != null || d != String.Empty)

This is always true as d cannot be both null and "" ;这总是正确的,因为d不能同时是null"" it has to be different from at least one of them.它必须与其中至少一个不同。

Some correct alternatives:一些正确的选择:

if (d != null && d != "")
if (!(d == null || d == ""))
if (!string.IsNullOrEmpty(d))

The problem is that you are using a logical OR when you should be using a logical AND.问题是当您应该使用逻辑 AND 时,您使用的是逻辑 OR。

You only want to add it when it is not null AND not empty.您只想在它不是 null 且不为空时添加它。

BTW: There is an easier way:顺便说一句:有一种更简单的方法:

foreach (var d in data)
{
      if (!String.IsNullOrEmpty(d))
      {
          ....

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

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