Find maximum value in list by condition LINQ VB.Net

Hobbyist_programmer 621 Reputation points

Hi All,

I have a list "ItemList" which has a property "Name" and "Pkeylist" PKeyList is a primary key for the list.

        Dim maxAmount = From item In itemList
                                        Where item.Name = "BOX"
                                        Select item.max(Function(x) x.PKeyList)

I would like to find the highest value for the group with Name "BOX" and get the max value form the PKeyList. How can i get that?


An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,553 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points

    you can user order by descending and take the first item like in following demo:

    Module Module62
      Sub Main()
          Call (New Demo).Execute()
        Catch ex As Exception
        End Try
        Console.WriteLine("Continue enter key")
      End Sub
      Friend Class Demo
        Friend Sub Execute()
          Dim itemList As New List(Of Data)
          itemList.Add(New Data With {.Name = $"BOX", .PKeyList = 1})
          itemList.Add(New Data With {.Name = $"BOX", .PKeyList = 3})
          itemList.Add(New Data With {.Name = $"BOX", .PKeyList = 2})
          Dim maxAmount = (From item In itemList
                           Where item.Name = "BOX"
                           Order By item.PKeyList Descending).First.PKeyList
        End Sub
      End Class
      Friend Class Data
        Friend Property Name As String
        Friend Property PKeyList As Integer
      End Class
    End Module

2 additional answers

Sort by: Most helpful
  1. Hobbyist_programmer 621 Reputation points

    Thanks peter for the time and effort for writing the whole answer . You could have written only the line "Order By item.PKeyList Descending).First.PKeyList" . Much appreciated.

    0 comments No comments

  2. Corey Burton 1 Reputation point

    Dim maxColumnValue As Object = (From x As Class In list(of Class) Select x.ColumnName Order By ColumnName Descending).First


    Dim maxColumnValue As Object = (From x As Class In list(of Class) Select x.ColumnName Order By ColumnName ).Last

    0 comments No comments