<< Back to VBNET
VB.NET LINQ Examples
Use LINQ, a set of extensions to the language that enables query expressions.LINQ. This stands for Language Integrated Query. We import the System.Linq namespace. This provides many extension methods, ones that act on collections.
LINQ allows queries. In a query expression, we describe a command in terms of the desired result. So we can say "get all items greater than 10" rather than use a loop.
A query. This example uses a query expression. The "result" Dim is assigned to a query's result: it uses a special syntax form. It examines all array elements, naming each "v."
Where: It then uses the Where keyword to filter elements. It only accepts elements greater than or equal to 10.
So: When we evaluate the "result" value in our For-Each loop, we see only the elements that the query selected. These are 10 and 100.
For Each, ForVB.NET program that uses query
Imports System.Linq
Module Module1
Sub Main()
' An array of 4 elements.
Dim values() As Integer = {1, 10, 100, 5}
' Gets all values greater than 9.
Dim result = From v In values Where v >= 10
' Display all matching Integers.
For Each value As Integer In result
Console.WriteLine(value)
Next
End Sub
End Module
Output
10
100
Order By. With Order By we can sort the results of a query. This statement comes after other query clauses like "Where." By default it is Ascending, ordering from low to high.
VB.NET program that uses Order By
Imports System.Linq
Module Module1
Sub Main()
Dim values() As Integer = {3, 10, -1, 30, -3}
' Order the elements from low to high (ascending).
Dim result = From v In values Order By v
For Each value As Integer In result
Console.WriteLine(value)
Next
End Sub
End Module
Output
-3
-1
3
10
30
Descending. We can apply the Descending keyword to an Order By clause in a query expression. This orders the elements from last to first (for strings, "Z" to "A").
Tip: For numbers, Descending orders from largest to smallest. Strings use a reverse alphabetical sort.
VB.NET program that uses order by, descending
Imports System.Linq
Module Module1
Sub Main()
Dim animals() As String = {"cat", "turtle", "ant"}
' Sort animals alphabetically, last to first.
Dim result = From a In animals
Order By a Descending
For Each value As String In result
Console.WriteLine(value)
Next
End Sub
End Module
Output
turtle
cat
ant
Group By, Into. With a query, we can also group elements together into automatically-generated groups. The syntax is confusing. We use the "Group" keyword twice—once for naming the group.
By: After By, we specify the property that will be used to separate groups (here I use Item1, part of the tuples).
TupleInto: In this part of the Group clause, we assign an identifier to the group—it can be any valid identifier (I use "TupleGroup").
TupleGroup: Each group contains a collection called TupleGroup (named in the program). We loop over it to display all values.
VB.NET program that uses Group, By, Into
Module Module1
Sub Main()
' Create list of tuples with two items each.
Dim list = New List(Of Tuple(Of Integer, String))
list.Add(New Tuple(Of Integer, String)(5, "green"))
list.Add(New Tuple(Of Integer, String)(5, "blue"))
list.Add(New Tuple(Of Integer, String)(20, "orange"))
list.Add(New Tuple(Of Integer, String)(20, "yellow"))
list.Add(New Tuple(Of Integer, String)(20, "magenta"))
' Group tuples by their first item.
' ... TupleGroup is an identifier name.
Dim result = From v In list
Group v By v.Item1 Into TupleGroup = Group
' Loop over each group and its items.
For Each value In result
Console.WriteLine(value.Item1)
For Each item In value.TupleGroup
Console.WriteLine(" " + item.Item2)
Next
Next
End Sub
End Module
Output
5
green
blue
20
orange
yellow
magenta
Extensions. The System.Linq namespace also gives us many extension methods. In VB.NET we do not need to import the System.Linq namespace to use these extensions.
Extension MethodTip: These extensions, like Average(), act upon any collection of type IEnumerable. An array, List, or query result qualifies.
ArrayListIEnumerableHere: We use Average to compute the average number in an array of 4 Integers. The average, a Double, happens to equal 5.
VB.NET program that uses average extension
Module Module1
Sub Main()
Dim numbers() As Integer = {2, 4, 6, 8}
' Use the Average extension from System.Linq.
Dim average As Double = numbers.Average()
Console.WriteLine(average)
End Sub
End Module
Output
5
Chain extensions. Extension methods, like those found in LINQ, often return the results of their invocation. So we can call further extensions on them.
Here: Take() returns the first three elements, in an IEnumerable collection. So Average() can be invoked on its result.
VB.NET program that chains extension methods
Module Module1
Sub Main()
Dim elements() As Integer = {5, 10, 15, 20, 25}
' Take first 3 numbers and average them.
Dim averageFirstThree = elements.Take(3).Average()
Console.WriteLine(averageFirstThree)
End Sub
End Module
Output
10
Any extension, lambda. The Any method returns True if the condition evaluates to True for any element in a sequence. This extension method can be used with a lambda expression.
LambdaFunc, Action, PredicateVB.NET program that uses Any, Func
Module Module1
Sub Main()
Dim values() As Integer = {10, -200, 1, 30, -1}
' See if the array has a negative number.
Dim hasNegative = values.Any(Function(x As Integer)
Return x < 0
End Function)
Console.WriteLine(hasNegative)
End Sub
End Module
Output
True
Query and extension call. We can combine query syntax with extension method calls. Consider this example—it orders the numbers with a query expression (Order By).
Then: It uses the Take() extension upon the result of the query expression. This style is sometimes useful.
VB.NET program that uses query, extension method
Imports System.Linq
Module Module1
Sub Main()
Dim numbers() As Integer = {5, 10, 1}
' Take first two numbers from ordered query.
Dim result = (From n In numbers
Order By n).Take(2)
For Each value As Integer In result
Console.WriteLine(value)
Next
End Sub
End Module
Output
1
5
FirstOrDefault. This is a useful LINQ extension method—it can help in many VB.NET programs. We call it on an IEnumerable instance. It has 2 possible results.
Result 1: If there is a first element in the collection (it has 1 or more elements), that value is returned by FirstOrDefault.
Result 2: If no first element exists (it has 0 elements total) the default value is returned. For int, this means we get a 0.
VB.NET program that uses FirstOrDefault
Module Module1
Sub Main()
Dim elements() As Integer = {5, 10, 15, 20, 25}
' Get first element safely.
Dim first1 = elements.FirstOrDefault()
Console.WriteLine("FIRSTORDEFAULT: {0}", first1)
elements = {}
' If no first element is present, we get the default value 0.
Dim first2 = elements.FirstOrDefault()
Console.WriteLine("FIRSTORDEFAULT: {0}", first2)
End Sub
End Module
Output
FIRSTORDEFAULT: 5
FIRSTORDEFAULT: 0
ElementAtOrDefault. Here we use the ElementAt and ElementAtOrDefault functions. Most developers will find ElementAtOrDefault to be the more useful form.
Info: We call ElementAtOrDefault twice. If the index is in the range of the collection, it returns the string at that index.
And: If the index if out-of-range, it returns the default value, which for a string is null (which is not displayed).
ElementAt: This is the same as ElementAtOrDefault but will throw an exception if we pass an index that is not within the collection's size.
VB.NET program that uses ElementAt, ElementAtOrDefault
Module Module1
Sub Main()
Dim sizes = {"small", "medium", "large"}
' Use the safe ElementAtOrDefault function.
Dim element1 = sizes.ElementAtOrDefault(1)
Console.WriteLine("ELEMENTATORDEFAULT: {0}", element1)
Dim element100 = sizes.ElementAtOrDefault(100)
Console.WriteLine("ELEMENTATORDEFAULT: {0}", element100)
' Use ElementAt, which may throw an exception if out-of-range.
Dim element2 = sizes.ElementAt(2)
Console.WriteLine("ELEMENTAT: {0}", element2)
End Sub
End Module
Output
ELEMENTATORDEFAULT: medium
ELEMENTATORDEFAULT:
ELEMENTAT: large
ToArray, ToList. Some extension methods from System.Linq convert collections. With ToArray and ToList, we convert from an IEnumerable to an array or List. Many types implement IEnumerable.
ToArrayToList
Enumerable.Range. Suppose we want an IEnumerable collection with a range of values. Or perhaps we want a repeated value many times—we like a certain number. We can use Range or Repeat.
Range, Repeat, Empty
System.Xml.Linq. The System.Xml.Linq namespace contains the XElement type. With XElement we can load XML, even from the network, and query it with LINQ.
XElementA summary. Many programs need no LINQ features: query expressions and extensions are not always useful. But these features have power. They make some programs shorter, easier to read.
Performance. Often LINQ features do not lead to the best performance. Using iterative statements, like for loops, and maintaining state in local variables is often faster.
Related Links:
- VB.NET Nullable
- VB.NET Convert Char Array to String
- VB.NET Object Array
- VB.NET File.ReadAllText, Get String From File
- VB.NET Compress File: GZipStream Example
- VB.NET Console.WriteLine (Print)
- VB.NET File.ReadLines Example
- VB.NET AddressOf Operator
- VB.NET Recursion Example
- VB.NET Recursive File Directory Function
- VB.NET Regex, Read and Match File Lines
- VB.NET Regex.Matches Quote Example
- VB.NET Regex.Matches: For Each Match, Capture
- VB.NET Convert String, Byte Array
- VB.NET File Size: FileInfo Example
- VB.NET File Handling
- VB.NET String.Format Examples: String and Integer
- VB.NET SyncLock Statement
- VB.NET TextInfo Examples
- VB.NET Array.Copy Example
- VB.NET HtmlEncode, HtmlDecode Examples
- VB.NET HtmlTextWriter Example
- VB.NET Stack Type
- VB.NET Func, Action and Predicate Examples
- VB.NET Function Examples
- VB.NET GoTo Example: Labels, Nested Loops
- VB.NET Array.Find Function, FindAll
- VB.NET HttpClient Example: System.Net.Http
- VB.NET DataColumn Class
- VB.NET DataGridView
- VB.NET DataSet Examples
- VB.NET DataTable Select Function
- VB.NET DataTable Examples
- VB.NET Attribute Examples
- VB.NET OpenFileDialog Example
- VB.NET Benchmark
- VB.NET BinaryReader Example
- VB.NET BinarySearch List
- VB.NET BinaryWriter Example
- VB.NET Regex.Replace Function
- VB.NET Regex.Split Examples
- VB.NET Regex.Match Examples: Regular Expressions
- VB.NET Convert ArrayList to Array
- VB.NET Array Examples, String Arrays
- VB.NET ArrayList Examples
- VB.NET Boolean, True, False and Not (Return True)
- VB.NET Nothing, IsNothing (Null)
- VB.NET Directive Examples: Const, If and Region
- VB.NET Do Until Loops
- VB.NET Do While Loop Examples (While)
- VB.NET Array.Resize Subroutine
- VB.NET Chr Function: Get Char From Integer
- VB.NET Class Examples
- VB.NET IndexOf Function
- VB.NET Insert String
- VB.NET Interface Examples (Implements)
- VB.NET 2D, 3D and Jagged Array Examples
- VB.NET Enum.Parse, TryParse: Convert String to Enum
- VB.NET Remove HTML Tags
- VB.NET Remove String
- VB.NET Event Example: AddHandler, RaiseEvent
- VB.NET Excel Interop Example
- VB.NET StartsWith and EndsWith String Functions
- VB.NET Initialize List
- VB.NET Number Examples
- VB.NET Optional String, Integer: Named Arguments
- VB.NET Replace String Examples
- VB.NET Exception Handling: Try, Catch and Finally
- VB.NET Enum Examples
- VB.NET Enumerable.Range, Repeat and Empty
- VB.NET Dictionary Examples
- VB.NET Double Type
- VB.NET LSet and RSet Functions
- VB.NET LTrim and RTrim Functions
- VB.NET Alphanumeric Sorting
- VB.NET PadLeft and PadRight
- VB.NET String.Concat Examples
- VB.NET String
- VB.NET Math.Abs: Absolute Value
- VB.NET Array.IndexOf, LastIndexOf
- VB.NET Remove Duplicate Chars
- VB.NET If Then, ElseIf, Else Examples
- VB.NET ParamArray (Use varargs Functions)
- VB.NET Integer.Parse: Convert String to Integer
- VB.NET ThreadPool
- VB.NET Process Examples (Process.Start)
- VB.NET TimeZone Example
- VB.NET Path Examples
- VB.NET ToArray Extension Example
- VB.NET ToCharArray Function
- VB.NET Stopwatch Example
- VB.NET Button Example
- VB.NET StreamReader ReadToEnd Function
- VB.NET ByVal Versus ByRef Example
- VB.NET StreamReader Example
- VB.NET StreamWriter Example
- VB.NET String.Compare Examples
- VB.NET Cast: TryCast, DirectCast Examples
- VB.NET String Constructor (New String)
- VB.NET String.Copy and CopyTo
- VB.NET Math.Ceiling and Floor: Double Examples
- VB.NET Math.Max and Math.Min
- VB.NET WebClient: DownloadData, Headers
- VB.NET Math.Round Example
- VB.NET Math.Truncate Method, Cast Double to Integer
- VB.NET Reverse String
- VB.NET Structure Examples
- VB.NET Sub Examples
- VB.NET Substring Examples
- VB.NET Convert Dictionary to List
- VB.NET Convert List and Array
- VB.NET Convert List to String
- VB.NET Convert Miles to Kilometers
- VB.NET Property Examples (Get, Set)
- VB.NET Remove Punctuation From String
- VB.NET Queue Examples
- VB.NET Const Values
- VB.NET Remove Duplicates From List
- VB.NET IComparable Example
- VB.NET ReDim Keyword (Array.Resize)
- VB.NET Contains Example
- VB.NET IEnumerable Examples
- VB.NET IsNot and Is Operators
- VB.NET String.IsNullOrEmpty, IsNullOrWhiteSpace
- VB.NET ROT13 Encode Function
- VB.NET StringBuilder Examples
- VB.NET Image Type
- VB.NET Val, Asc and AscW Functions
- VB.NET String.Empty Example
- VB.NET String.Equals Function
- VB.NET VarType Function (VariantType Enum)
- VB.NET With Statement
- VB.NET WithEvents: Handles and RaiseEvent
- VB.NET String Length Example
- VB.NET ToList Extension Example
- VB.NET ToLower and ToUpper Examples
- VB.NET TextBox Example
- VB.NET ToString Overrides Example
- VB.NET ToTitleCase Function
- VB.NET Convert String Array to String
- VB.NET Iterator Example: Yield Keyword
- VB.NET Mid Statement
- VB.NET Mod Operator (Odd, Even Numbers)
- VB.NET Convert String to Integer
- VB.NET Module Example: Shared Data
- VB.NET Integer
- VB.NET Keywords
- VB.NET Lambda Expressions
- VB.NET LastIndexOf Function
- VB.NET String Join Examples
- VB.NET Multiple Return Values
- VB.NET MustInherit Class: Shadows and Overloads
- VB.NET Namespace Example
- VB.NET KeyValuePair Examples
- VB.NET Environment.NewLine: vbCrLf
- VB.NET Levenshtein Distance Algorithm
- VB.NET Shared Function
- VB.NET Shell Function: Start EXE Program
- VB.NET Sleep Subroutine (Pause)
- VB.NET Sort Dictionary
- VB.NET Exit Statements
- VB.NET LINQ Examples
- VB.NET List Examples
- VB.NET Extension Method
- VB.NET Select Case Examples
- VB.NET MessageBox.Show Examples
- VB.NET Timer Examples
- VB.NET TimeSpan Examples
- VB.NET BackgroundWorker
- VB.NET String Between, Before and After Functions
- VB.NET CStr Function
- VB.NET DataRow Field Extension
- VB.NET DataRow Examples
- VB.NET DateTime Format
- VB.NET Char Examples
- VB.NET DateTime.Now Property (Today)
- VB.NET DateTime.Parse: Convert String to DateTime
- VB.NET DateTime Examples
- VB.NET Decimal Type
- VB.NET HashSet Example
- VB.NET Hashtable Type
- VB.NET Fibonacci Sequence
- VB.NET XmlWriter, Create XML File
- VB.NET File.Copy: Examples, Overwrite
- VB.NET File.Exists: Get Boolean
- VB.NET Path.GetExtension: File Extension
- VB.NET Tuple Examples
- VB.NET Trim Function
- VB.NET TrimEnd and TrimStart Examples
- VB.NET Word Count Function
- VB.NET Word Interop Example
- VB.NET For Loop Examples (For Each)
- VB.NET XElement Example
- VB.NET Truncate String
- VB.NET Sort Number Strings
- VB.NET Sort Examples: Arrays and Lists
- VB.NET SortedList
- VB.NET SortedSet Examples
- VB.NET Split String Examples
- VB.NET Uppercase First Letter
- VB.NET XmlReader, Parse XML File
- VB.NET ZipFile Example
- VB.NET Array.Reverse Example
- VB.NET Random Lowercase Letter
- VB.NET Byte Array: Memory Usage
- VB.NET Byte and Sbyte Types
- VB.NET Char Array
- VB.NET Random String
- VB.NET Random Numbers
- VB.NET Async, Await Example: Task Start and Wait
- VB.NET Choose Function (Get Argument at Index)
- VB.NET Sort by File Size
- VB.NET Sort List (Lambda That Calls CompareTo)
- VB.NET List Find and Exists Examples
- VB.NET Math.Sqrt Function
- VB.NET Loop Over String: For, For Each
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf