Determine Minimum and Maximum using LinQ PDF Print E-mail
Written by J. Bijvoets   
Saturday, 04 December 2010 09:18

How to determine Minimum and Maximum value using LinQ in Visual Basic

LinQ offers an easy method to determine the minimum and maximum values in a Datatable or array. This tutorial example shows how to use the min and max functions in LinQ.

For this example, I define a dataset DS. In this dataset is placed a table "Numbers", containing rows with just one field of type Integer:

'Initialisation

Dim TestDs as new Dataset

Dim t As New DataTable

t.TableName = "Numbers"
t.Columns.Add("number", GetType(Integer))
t.Rows.Add(0)
t.Rows.Add(2)
t.Rows.Add(5)
t.Rows.Add(3)
t.Rows.Add(1)
t.Rows.Add(9)

TestDs.Tables.Add(t)

Finding the Minimum value using LinQ

Now you can find the mimimum value using the min-function:

Dim msg As String = "", MinValue As Single, MaxValue As Single

Dim numbers = TestDs.Tables("Numbers").AsEnumerable()

MinValue = (From n In numbers Select n.Field(Of Integer)("number")).Min()

msg = String.Format("Min = {0}", MinValue)

MsgBox(msg) 'Shows 0 (Zero)

Finding the Maximum value using LinQ

Finding the maximum value using the max-function is done with the same ease:

MaxValue = (From n In numbers Select n.Field(Of Integer)("number")).Max()

msg = String.Format("Max = {0}", MaxValue)

MsgBox(msg) 'Shows 9

Last Updated on Saturday, 04 December 2010 11:38