How to return a list from a public function in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Linq

Namespace ListReturnExample

    ''' <summary>
    ''' Represents a product in the system.
    ''' </summary>
    Public Class Product

        ''' <summary>
        ''' Gets or sets the product name.
        ''' </summary>
        Public Property Name As String

        ''' <summary>
        ''' Gets or sets the product price.
        ''' </summary>
        Public Property Price As Decimal

    End Class

    ''' <summary>
    ''' Provides product-related business operations.
    ''' </summary>
    Public Class ProductService

        ''' <summary>
        ''' Returns all products having a price greater than or equal to the specified minimum price.
        ''' </summary>
        ''' <param name="minimumPrice">
        ''' The minimum price required for a product to be included.
        ''' </param>
        ''' <returns>
        ''' A list of matching products.
        ''' </returns>
        ''' <exception cref="ArgumentOutOfRangeException">
        ''' Thrown when minimumPrice is less than zero.
        ''' </exception>
        Public Function GetProductsByMinimumPrice(minimumPrice As Decimal) As List(Of Product)

            If minimumPrice < 0 Then
                Throw New ArgumentOutOfRangeException(
                    NameOf(minimumPrice),
                    "Minimum price cannot be negative.")
            End If

            ' Sample data.
            Dim products As New List(Of Product) From {
                New Product With {.Name = "Laptop", .Price = 1200D},
                New Product With {.Name = "Mouse", .Price = 25D},
                New Product With {.Name = "Keyboard", .Price = 80D},
                New Product With {.Name = "Monitor", .Price = 300D}
            }

            ' Filter and return matching products.
            Return products.
                Where(Function(p) p.Price >= minimumPrice).
                ToList()

        End Function

    End Class

    Module Program

        Sub Main()

            Try
                Dim productService As New ProductService()

                ' Call the public function that returns a List(Of Product).
                Dim filteredProducts As List(Of Product) =
                    productService.GetProductsByMinimumPrice(100D)

                For Each product As Product In filteredProducts
                    Console.WriteLine($"{product.Name} - ${product.Price}")
                Next

            Catch ex As Exception
                Console.WriteLine($"Error: {ex.Message}")
            End Try

        End Sub

    End Module

End Namespace
                 
                     
'
' run:
'
' Laptop - $1200
' Monitor - $300
'

 



answered Oct 1 by avibootz
...