本文整理汇总了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)
输出:
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.")
输出:
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}")
输出:
The value of the firstMonth1 variable is 1 The value of the firstMonth2 variable is 1