LINQ To DataSet Samples - Element OperatorsOn This Page |
This sample uses First to return the first matching DataRow, instead of as a sequence of DataRows.
Public Sub DataSetLinq58()
Dim products = TestDS.Tables("Products").AsEnumerable()
Dim product12 As DataRow = (From p In products _
Where p!ProductID = 12 _
Select p).First()
Console.WriteLine("Product ID: {0} UnitsInStock: {1} ", product12!ProductId, product12!UnitsInStock)
End Sub
Result:
Product ID: 12 UnitsInStock: 86
This sample uses First to find the first DataRow in the DataTable that contains a value that starts with 'o'.
Public Sub DataSetLinq59()
Dim strings = TestDS.Tables("Digits").AsEnumerable()
Dim startsWithO = strings.First(Function(s) s.Field(Of String)("digit")(0) = "o"c)
Console.WriteLine("A string starting with 'o': " & startsWithO("digit"))
End Sub
Result:
A string starting with 'o': one
This sample uses FirstOrDefault to try to return the first DataRow of the source DataTable, unless there are no DataROws, in which case the default value of nothing is returned
Public Sub DataSetLinq61()
Dim emptyTable = TestDS.Tables("EmptyDataTable").AsEnumerable()
Dim firstNumOrDefault = emptyTable.FirstOrDefault()
Console.WriteLine(firstNumOrDefault Is Nothing)
End Sub
Result:
True
This sample uses ElementAt to retrieve the second number greater than 5 from an DataTable.
Public Sub DataSetLinq64()
Dim numbers = TestDS.Tables("Numbers").AsEnumerable()
Dim fourthLowNum = (From n In numbers _
Where n!number > 5 _
Select n).ElementAt(1) ' second number is index 1 because sequences use 0-based indexing
Console.WriteLine("Second number > 5: " & fourthLowNum!number)
End Sub
Result:
Second number > 5: 8