Find maximum value in list by condition LINQ VB.Net

Hobbyist_programmer 621 Reputation points
2020-12-04T15:41:25.477+00:00

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?

Thanks

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

Accepted answer
  1. Peter Fleischer (former MVP) 19,316 Reputation points
    2020-12-04T15:58:01.37+00:00

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

    Module Module62
      Sub Main()
        Try
          Call (New Demo).Execute()
        Catch ex As Exception
          Console.WriteLine(ex.ToString)
        End Try
        Console.WriteLine("Continue enter key")
        Console.ReadKey()
      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
          Console.WriteLine(maxAmount)
        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
    2020-12-04T16:07:59.13+00:00

    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
    2021-02-01T21:36:12.777+00:00

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

    or

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

    0 comments No comments