本文整理匯總了VB.NET中System.Linq.Queryable.DefaultIfEmpty方法的典型用法代碼示例。如果您正苦於以下問題:VB.NET Queryable.DefaultIfEmpty方法的具體用法?VB.NET Queryable.DefaultIfEmpty怎麽用?VB.NET Queryable.DefaultIfEmpty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。
在下文中一共展示了Queryable.DefaultIfEmpty方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的VB.NET代碼示例。
示例1: List
Structure Pet
Public Name As String
Public Age As Integer
End Structure
Shared Sub DefaultIfEmptyEx1()
' Create a list of Pet objects.
Dim pets As New List(Of Pet)(New Pet() { _
New Pet With {.Name = "Barley", .Age = 8}, _
New Pet With {.Name = "Boots", .Age = 4}, _
New Pet With {.Name = "Whiskers", .Age = 1}})
' Call DefaultIfEmtpy() on the collection that Select()
' returns, so that if the initial list is empty, there
' will always be at least one item in the returned array.
Dim names() As String = pets.AsQueryable() _
.Select(Function(Pet) Pet.Name) _
.DefaultIfEmpty() _
.ToArray()
Dim first As String = names(0)
MsgBox(first)
' This code produces the following output:
'
' Barley
End Sub
示例2: oldPets
' Create a list of Pet objects.
Dim pets As New List(Of Pet)(New Pet() { _
New Pet With {.Name = "Barley", .Age = 8}, _
New Pet With {.Name = "Boots", .Age = 4}, _
New Pet With {.Name = "Whiskers", .Age = 1}})
' This query returns pets that are 10 or older. In case there are no pets
' that meet that criteria, call DefaultIfEmpty(). This code passes an (optional)
' default value to DefaultIfEmpty().
Dim oldPets() As String = pets.AsQueryable() _
.Where(Function(Pet) Pet.Age >= 10) _
.Select(Function(Pet) Pet.Name) _
.DefaultIfEmpty("[EMPTY]") _
.ToArray()
Try
MsgBox("First query: " + oldPets(0))
Catch ex As Exception
Console.WriteLine("First query: An exception was thrown: " + ex.Message)
End Try
' This query selects only those pets that are 10 or older.
' This code does not call DefaultIfEmpty().
Dim oldPets2() As String = _
pets.AsQueryable() _
.Where(Function(Pet) Pet.Age >= 10) _
.Select(Function(Pet) Pet.Name) _
.ToArray()
' There may be no elements in the array, so directly
' accessing element 0 may throw an exception.
Try
MsgBox("Second query: " + oldPets2(0))
Catch ex As Exception
MsgBox("Second query: An exception was thrown: " + ex.Message)
End Try
輸出:
First(query) : [EMPTY] Second query: An exception was thrown: Index was outside the bounds of the array.