當前位置: 首頁>>代碼示例>>VB.NET>>正文


VB.NET Enumerable.FirstOrDefault方法代碼示例

本文整理匯總了VB.NET中System.Linq.Enumerable.FirstOrDefault方法的典型用法代碼示例。如果您正苦於以下問題:VB.NET Enumerable.FirstOrDefault方法的具體用法?VB.NET Enumerable.FirstOrDefault怎麽用?VB.NET Enumerable.FirstOrDefault使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。


在下文中一共展示了Enumerable.FirstOrDefault方法的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的VB.NET代碼示例。

示例1: numbers

' Create an empty array.
Dim numbers() As Integer = {}

' Select the first element in the array, or a default value
' if there are not elements in the array.
Dim first As Integer = numbers.FirstOrDefault()

' Display the output.
Console.WriteLine(first)
開發者ID:VB.NET開發者,項目名稱:System.Linq,代碼行數:9,代碼來源:Enumerable.FirstOrDefault

輸出:

0

示例2: names

' Create an array of strings.
Dim names() As String =
{"Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu"}

' Select the first string in the array whose length is greater than 20.
Dim firstLongName As String =
names.FirstOrDefault(Function(name) name.Length > 20)

' Display the output.
Console.WriteLine($"The first long name is {firstLongName}")

' Select the first string in the array whose length is greater than 30,
' or a default value if there are no such strings in the array.
Dim firstVeryLongName As String =
names.FirstOrDefault(Function(name) name.Length > 30)

Dim text As String = IIf(String.IsNullOrEmpty(firstVeryLongName), "not a", "a")

Console.WriteLine($"There is {text} name longer than 30 characters.")
開發者ID:VB.NET開發者,項目名稱:System.Linq,代碼行數:19,代碼來源:Enumerable.FirstOrDefault

輸出:

The first long name is Andersen, Henriette Thaulow

There is not a name longer than 30 characters.

示例3: List

Dim months As New List(Of Integer)(New Integer() {})

' Setting the default value to 1 after the query.
Dim firstMonth1 As Integer = months.FirstOrDefault()
If firstMonth1 = 0 Then
    firstMonth1 = 1
End If
Console.WriteLine($"The value of the firstMonth1 variable is {firstMonth1}")

' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim firstMonth2 As Integer = months.DefaultIfEmpty(1).First()
Console.WriteLine($"The value of the firstMonth2 variable is {firstMonth2}")
開發者ID:VB.NET開發者,項目名稱:System.Linq,代碼行數:12,代碼來源:Enumerable.FirstOrDefault

輸出:

The value of the firstMonth1 variable is 1
The value of the firstMonth2 variable is 1


注:本文中的System.Linq.Enumerable.FirstOrDefault方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。