Monday, April 4, 2016

Return Top 3 largest values in an array using LINQ

Sample snippet on getting the three largest values in an array using LINQ.

VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Dim rand As New Random()
Dim numbers As New List(Of Int32)
For index = 1 To 20 Step 1
    ' add a list item which is a number from 1 through 100 
    numbers.Add(rand.Next(1, 100))
Next
 
Dim topThreeLargest = numbers.OrderByDescending(Function(t) t).Take(3)
Console.WriteLine("Top three largest elements in the array: ")
 
For Each item As String In topThreeLargest
    Console.WriteLine(item)
Next

0 comments:

Post a Comment