我有一個變量對象列表SanityResults
只有一個對象的值爲空,我試圖驗證這個條件爲if (SanityResults != null)
,但失敗?如何檢查這種情況?如何檢查值爲空的對象列表?
if (SanityResults != null)
{
//code
}
我有一個變量對象列表SanityResults
只有一個對象的值爲空,我試圖驗證這個條件爲if (SanityResults != null)
,但失敗?如何檢查這種情況?如何檢查值爲空的對象列表?
if (SanityResults != null)
{
//code
}
您使用會檢查是否SanityResults
爲空或不是條件。但是你想檢查列表中所有對象的屬性。所以,更好的選擇是,如果你想檢查檢查任何對象內部列表爲空意味着你必須使用類似下面使用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
}
的問題是,所述SanityResults實際上是不爲空,並且由一個元件的具有屬性,即是空。
允許哪些元素爲null,哪些不是?
如果沒有屬性都允許爲空,然後用此去:具有
if(SanityResults.Any(x => x.failCount == null || x.passcount == null || x.testsuitename == null || x.htmllist == null))
{
// Code goes here
}
的元素在列表中,不過是空值,但在代碼中有一個語義值,聞起來有點。
創建的是一個單獨的方法包含空
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;
}}
我建議的唯一編輯方法是首先檢查myList是否爲null,然後在第一個foreach中檢查myObject是否爲空(如果上述任一情況屬實,您的答案將會拋出異常,當它應該只是返回真正的恕我直言)。 –
好吧,只是拋出另一個類似的答案進入環...
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',那麼'SanityResults.Any'將會拋出'NullReference'。另外需要注意的是,如果任何'sr'爲null,那麼它的屬性將拋出'NullReference'。對? –
沒有。只要任何條件的計算結果爲「true」('true || false == true'),'||'運算符就返回'true',就像'&&'運算符在任何條件計算結果爲false時一樣返回'false' '('false && true == false')。所以不會有'NullReference'異常,因爲我正在測試「child」對象之前的「parent」對象。 –
很好,謝謝你提供的信息 –
的IEnumerable的樂趣 – FrankerZ
檢查列表中是否有任何項是無效的,因爲它是項目的*屬性*,不應該爲null。 –
@ J.N .:如果該項目本身爲空,則不會有任何屬性 –