VB.NET LINQ WHERE query collection with various keys throws KeyNotFoundException

Viewed 97

I would like to select first element from collection using LINQ WHERE function and lambda, but some elements doesn't have subjected key (only one of them has it) - and so I'm receiving KeyNotFoundException error... ;-/ see collection structure

Is there any way how to solve it?

views.First(Function(x) x("DefaultView").ToString = "TRUE")
... threw an exception of type 'System.Collections.Generic.KeyNotFoundException'

Thanks. #JK

2 Answers

You should be able to do

views.FirstOrDefault(Function(x As Dictionary(Of String, Object))
                         Return x.ContainsKey("DefaultView") AndAlso x("DefaultView").ToString() = "TRUE"
                     End Function)

ContainsKey ensures that the Key exists in the Dictionary.
AndAlso will only check the second condition if ContainsKey returns true
x("DefaultView") will no longer error because we know it exists

To avoid double lookup in the dictionary.

views.FirstOrDefault(Function(x) 
                        Dim value
                        Return x.TryGetValue("DefaultView", value) AndAlso value.ToString() = "TRUE"
                    End Function)
Related