+92 332 4229 857 99ProjectIdeas@Gmail.com

Applying LINQ On Class (Vb.net)



In the following code applying a queries on user defined class. A Player class contains name of person and the score list. Getting those players who have average > 160 and getting those players who have max score etc..





 

Public Class Player

    Private _Name As String = Nothing

        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value
            End Set
        End Property

    Private _scores As List(Of Integer)

        Public Property Scores() As List(Of Integer)
            Get
                Return _scores
            End Get
            Set(ByVal value As List(Of Integer))
                _scores = value
            End Set
        End Property

End Class

Sub Main()

' Defining List Of PlayerObject
Dim players As List(Of Player) = New List(Of Player)

' Defining Each Player Name And Score
  Dim p1 As New Player With {.Name = "Osama", _
                                   .Scores = New List(Of Integer)}
        p1.Scores.Add(120)
        p1.Scores.Add(130)
        p1.Scores.Add(290)

  Dim p2 As New Player With {.Name = "Saad", _
                                   .Scores = New List(Of Integer)}
        p2.Scores.Add(220)
        p2.Scores.Add(130)
        p2.Scores.Add(590)

  Dim p3 As New Player With {.Name = "Maryam", _
                                   .Scores = New List(Of Integer)}
        p3.Scores.Add(100)
        p3.Scores.Add(240)
        p3.Scores.Add(200)

  ' Now adding all defined players to List of PlayerObject
        players.Add(p1)
        players.Add(p2)
        players.Add(p3)

' Now Applying Queries
'First Query: Displaying Players who have scores average greater than 160
Dim firstQuery = _
            From p As Player In players _
            Where p.Scores.Average > 160 _
            Select p

    ' Displaying the player name and his/her score average
    For Each p In firstQuery
        Console.WriteLine(p.Name & " " & p.Scores.Average())
    Next

'Second Query: Displaying Players who have max score greater than 300

Dim secondQuery = _
            From p As Player In players _
            Where p.Scores.Max > 300 _
            Select p

   ' Displaying the player name and his/her max score
    For Each p In secondQuery
        Console.WriteLine(p.Name & " " & p.Scores.Max())
    Next

'Third Query: Displaying Those Players whose name starts with (S) Letter

Dim thirdQuery = _
            From p As Player In players _
            Where p.Name.StartsWith("S") _
            Select p
   ' Displaying the player name starting with 'S' and his/her max score
    For Each p In thirdQuery
        Console.WriteLine(p.Name & " " & p.Scores.Max())
    Next


End Sub


0 comments: