Sequence contains no elements

Select

Image via Wikipedia

The error occurs when you try to access an object returned by a Linq query with 0 elements in the result set an
InvalidOperationException is thrown. Below is a simulation to generate the error:

Dim productQuery = From p In context.Products Where p.ID = -1 Select p

Dim p As Product = productQuery.Single()

An exception is thrown by the Single() method because the productQuery object has no products inside and the Single() method is
trying to reach the first entity in the productQuery.

To avoid this problem, we must check whether productQuery is containing some items or not. Here is the correct way to do it:

                                    Dim productQuery = From p In context.Products Where p.ID = -1 Select p 
                                    If productQuery.Count > 0 Then
                                            Dim p As Product = productQuery.Single()
                                    Else
                                            Return Nothing
                                    End If

Cross Product of arrays using LINQ

Cross Product is usually a database operation on two tables similar to a Join operation with the only difference is that the cross product will yield all the possible combinations  between the two tables. Database Management Systems such as SQL Server and Oracle provided the cross product operation easily using the cross join keyword. The problem however in real life applications appears when we want to do cross product within the application logic. Suppose you have two arrays of numbers and you want to find out all the possible combinations of the two arrays together, then pick one of those combinations that meet your specific business needs. Fortunately, with the introduction of LINQ in the past few years, cross product has become as simple as writing any other naive query. Lets take a look at the example below: consider two arrays A and B having 4 values each:

        Dim A() As Integer = {1, 2, 3, 4}
        Dim b() As Integer = {5, 6, 7, 8}

Cross product is simply obtained using the following LINQ query followed by writing out the results to console:

        Dim crossProduct = From x In A, y In b Select x, y
        For Each i In crossProduct
            Console.WriteLine(i)
        Next

This will yield the following results: