2011-10-05 81 views
0
Public Class Inventory 
     Public Property Productcode As String 
     Public Property lstattribute As List(Of Attribute) 
End Class 
Public Class Attribute 
     Public Property Name As String 
     Public Property value As String 
End Class 

我有一個清單項目列表。 我試圖讓AttributeList中的最大數量的庫存清單lambda max count中的空引用

我用這個代碼

oLsInventory.OrderByDescending(Function(c) c.AttributeList.Count).FirstOrDefault().AttributeList.Count 

但如果我的屬性列表爲空。 lambda引發空引用。 有沒有辦法檢查lambda中的空引用?或者有沒有更好的方法來重寫上面的linq查詢?

感謝 Jothish

回答

0

這是我如何得到它的工作。 在訂購之前,我過濾了空對象。然後在該列表的頂部運行計數。

oLsInventory.FindAll(Function(c) c.AttributeList IsNot Nothing).OrderByDescending(Function(c) c.AttributeList.Count).Select(Function(c) c.AttributeList.Count).FirstOrDefault() 
0

移動FirstOrDefault到很後面,並使用Select你的存貨清單映射到屬性計數的列表。

' Returns 0 if the list is empty 
Dim max = oLsInventory.OrderByDescending(Function(c) c.AttributeList.Count) _ 
      .Select(Function(c) AttributeList.Count).FirstOrDefault() 

另一種選擇是:

  • 庫存列表中映射到屬性列表統計
  • 添加Integer.MinValue到列表
  • 執行Max()

    ' Returns Integer.MinValue if oLsInventory is empty 
    Dim maxValue = oLsInventory.Select(Function(c) AttributeList.Count) _ 
           .Union(New Integer() {Integer.MinValue}).Max() 
    
1

我會放置在最後的FirstOrDefault通過添加像這樣一個選擇:

oLsInventory.OrderByDescending(Function(c) c.AttributeList.Count).Select(Function(c) c.AttributeList.Count).FirstOrDefault() 
+0

感謝Aducci..but因爲AttributeList的是什麼,上面的代碼被扔error..I得到它的工作使用 - oLsInventory.FindAll(功能(C)c.AttributeList IsNot運算沒有).OrderByDescending(功能(C )c.AttributeList.Count).Select(Function(c)c.AttributeList.Count).FirstOrDefault() – JoR

+0

@JoR - 很高興您能夠找到答案。作爲答案發布您的解決方案並接受它。這將幫助有類似問題的人 – Aducci