Return Max value with LINQ Query in VB.NET?

21,883

You can use the DataSet Extensions for Linq to query a datatable.

The following query should help.

Dim query = _
    From value In dt.AsEnumerable() _
    Select value(Of Double)("ColumnName").Max();

If you don't now in which column will hold the maximum you could use: (C#)

var result = from r in table.AsEnumerable()
             select r.ItemArray.Max();
Share:
21,883
Vishal_Kotecha
Author by

Vishal_Kotecha

Updated on November 04, 2020

Comments

  • Vishal_Kotecha
    Vishal_Kotecha over 3 years

    I have a method that takes in an id, a start date, and and end date as parameters. It will return rows of data each corresponding to the day of the week that fall between the date range. The rows are all doubles. After returning it into a DataTable, I need to be able to use LINQ in VB.NET to return the maximum value. How can I achieve this? Here is the initial setup?

    Dim dt as DataTable = GetMaximumValue(1,"10/23/2011","11/23"/2011")
    
    'Do linq query here to return the maximum value
    

    The other alternative is to just return a Maximum value just given an id which would be slightly easier to implement, so the method would look like this:

    Dim dt as DataTable = GetMaximumValue(1)
    
    'Do linq query here to return maximum value
    

    Important

    What if I want to query against a DataRow instead of a DataTable and the column names are not the same, they are something like MaxForMon, MaxForTue, MaxForWed`, etc... and I need to take the Maximum value (whether it is MaxForMon, MaxForTue, or some other column). Would an option for this be to alias the column returned in the stored proc? The other thing I thought about was instead of doing this in LINQ, I probably should just handle it in the T-SQL.

  • Vishal_Kotecha
    Vishal_Kotecha over 12 years
    I will try this out. What if I instead what to query against a DataRow isntead of a DataTable?