簡體   English   中英

如何檢查值為空的對象的列表?

[英]How to check for a List of objects whose values are null?

我有一個變量SanityResults的對象列表,其中只有一個對象的值為null,我試圖驗證這種情況, if (SanityResults != null)但失敗了?如何檢查這種情況?

在此處輸入圖片說明

if (SanityResults != null)
{
     //code
}

您使用的條件將檢查SanityResults是否為null。 但是您想檢查列表中所有對象的屬性。 因此,更好的選擇是如果要檢查列表中是否存在任何對象為null的情況,則使用Any()意味着您必須像下面這樣使用:

if(SanityResults.Any(x => x == null))
{
   // This will execute if any one of the object in the list is null
}

現在,如果要檢查列表中每個對象的屬性,請嘗試以下操作:

if(SanityResults.Any(x => x.failCount==null || x.htmllist ==null))
{
    // include conditions like this for all required properties
    // this statement will execute if any of the property of any of the objects in the list is null
}

為創建單獨的方法包含null

public bool IsContainNull(List<SanityResults> myList)
{
    foreach(var myObject in myList)
    { 
     if(myObject==null) 
      {return false;} 
     else{ 
      foreach(PropertyInfo pi in myObject.GetType().GetProperties())
            {
                if(pi.PropertyType == typeof(string))
                {
                    string stringValue = (string)pi.GetValue(myObject);
                    if(string.IsNullOrEmpty(stringValue ))
                    {
                        return true;
                    }
                }
               else if(pi.PropertyType == typeof(int))
                {
                    int intValue = (int)pi.GetValue(myObject);
                    if(intValue==null)
                    {
                        return true;
                    }
                }
            }

    }
            return false; 

}}

好吧,只是把另一個類似的答案扔進去...

if (SanityResults == null || SanityResults.Any(sr => sr == null) || 
    SanityResults.Any(sr => sr.failcount == null && sr.htmllist == null &&
    sr.passcount == null && sr.testsuitename == null))
{
   // Do something if the List is null, if any items in the list are null, 
   // or all of the properties of any item in the list are null
}

問題在於SanityResults實際上不是null,並且由一個具有屬性的元素組成,這些元素為null。

哪些元素可以為null,哪些不允許為null?

如果所有屬性都不允許為null,請執行以下操作:

if(SanityResults.Any(x => x.failCount == null || x.passcount == null || x.testsuitename == null || x.htmllist == null))
{
    // Code goes here
}

列表中的一個元素,除了空值之外,什么都沒有,但是在代碼中具有語義值,但是有點味道。

暫無
暫無

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

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