Null reference in lambda max count
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
I have a list of inventory items. I am trying to get the max count of attributelist in the inventory list
I used this code
oLsInventory.OrderByDescending(Function(c) c.AttributeList.Count).FirstOrDefault().AttributeList.Count
But if my attribute list null. The lambda throws null reference. Is there any way to check for null reference in lambda ? Or is there a better way to rewrite the above开发者_如何学Go linq query ?
Thanks Jothish
I would place the FirstOrDefault at the very end by adding a Select like so:
oLsInventory.OrderByDescending(Function(c) c.AttributeList.Count).Select(Function(c) c.AttributeList.Count).FirstOrDefault()
Move FirstOrDefault
to the very back and use Select
to map your list of Inventories to a list of attribute counts.
' Returns 0 if the list is empty
Dim max = oLsInventory.OrderByDescending(Function(c) c.AttributeList.Count) _
.Select(Function(c) AttributeList.Count).FirstOrDefault()
Another option is to:
- map the list of inventories to a list of attribute counts
- add
Integer.MinValue
to the list execute
Max()
:' Returns Integer.MinValue if oLsInventory is empty Dim maxValue = oLsInventory.Select(Function(c) AttributeList.Count) _ .Union(New Integer() {Integer.MinValue}).Max()
This is how I got it working. Before ordering I filtered the null objects..then ran the count on top of that list.
oLsInventory.FindAll(Function(c) c.AttributeList IsNot Nothing).OrderByDescending(Function(c) c.AttributeList.Count).Select(Function(c) c.AttributeList.Count).FirstOrDefault()
精彩评论