簡體   English   中英

IF 語句檢查 null 或 String.Empty

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

所以我有一個列表,其中包含一些數據,例如輸入路徑、output 路徑以及列標題。 可以看出有六個列標題,但有些可能是 null,因為它們不必使用。 因此,我創建了一種過濾數據的方法,以便只保留有用的數據。

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

為什么當我將 List data傳遞給此方法時,沒有任何數據被過濾,因此filteredData將包含與data相同的內容,但是當我使用以下內容時(如果語句僅評估非空),它會正確過濾?

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

謝謝

你:

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

這總是正確的,因為d不能同時是null"" 它必須與其中至少一個不同。

一些正確的選擇:

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

問題是當您應該使用邏輯 AND 時,您使用的是邏輯 OR。

您只想在它不是 null 且不為空時添加它。

順便說一句:有一種更簡單的方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM