How to select N random elements from a List<T> in VB.NET

2 Answers

0 votes
' ============================================================
' Title: Select N Random Elements from a List(Of T)
' Author: Example Program
' Description:
'   Demonstrates how to randomly select N unique elements
'   from a List(Of T) using VB.NET.
'
' Best Practices Used:
'   - Generic method for reusability
'   - Input validation
'   - Clear comments and documentation
'   - Random.Shared for modern .NET applications
' ============================================================

Imports System
Imports System.Linq
Imports System.Collections.Generic

Module Program

    Sub Main()

        ' Create a sample list.
        Dim fruits As New List(Of String) From {
            "Apple",
            "Banana",
            "Orange",
            "Mango",
            "Grape",
            "Pineapple",
            "Peach",
            "Cherry",
            "Kiwi",
            "Strawberry"
        }

        ' Number of random items to select.
        Dim numberToSelect As Integer = 3

        Try

            ' Get random items.
            Dim selectedItems As List(Of String) =
                GetRandomElements(fruits, numberToSelect)

            Console.WriteLine("Original List:")
            For Each fruit In fruits
                Console.WriteLine($"  {fruit}")
            Next

            Console.WriteLine()
            Console.WriteLine($"Randomly Selected {numberToSelect} Items:")

            For Each item In selectedItems
                Console.WriteLine($"  {item}")
            Next

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

    End Sub

    ''' <summary>
    ''' Returns N unique random elements from a list.
    ''' </summary>
    ''' <typeparam name="T">The type stored in the list.</typeparam>
    ''' <param name="source">Source list.</param>
    ''' <param name="count">Number of elements to select.</param>
    ''' <returns>A list containing randomly selected elements.</returns>
    Private Function GetRandomElements(Of T)(
        source As List(Of T),
        count As Integer) As List(Of T)

        ' Validate input.
        If source Is Nothing Then
            Throw New ArgumentNullException(NameOf(source))
        End If

        If count < 0 OrElse count > source.Count Then
            Throw New ArgumentException(
                "Count must be between 0 and the number of items in the list.")
        End If

        ' Create a copy so the original list is not modified.
        Dim shuffled As New List(Of T)(source)

        ' Fisher-Yates shuffle algorithm.
        For i As Integer = shuffled.Count - 1 To 1 Step -1
            Dim j As Integer = Random.Shared.Next(i + 1)

            ' Swap elements.
            Dim temp As T = shuffled(i)
            shuffled(i) = shuffled(j)
            shuffled(j) = temp
        Next

        ' Return the first N items from the shuffled list.
        Return shuffled.Take(count).ToList()

    End Function

End Module


' run:
'
' Original List:
'   Apple
'   Banana
'   Orange
'   Mango
'   Grape
'   Pineapple
'   Peach
'   Cherry
'   Kiwi
'   Strawberry
' 
' Randomly Selected 3 Items:
'   Orange
'   Grape
'   Strawberry
'

 



answered Oct 9 by avibootz
0 votes
' ============================================================
' Title: Select N Random Elements from a List(Of T)
' Author: Example Program
' Description:
'   Demonstrates how to randomly select N unique elements
'   from a List(Of T) using VB.NET.
'
' Best Practices Used:
'   - Generic method for reusability
'   - Input validation
'   - Clear comments and documentation
'   - Random.Shared for modern .NET applications
' ============================================================

Imports System
Imports System.Collections.Generic

Module Program

    Sub Main()

        ' Create a sample list.
        Dim fruits As New List(Of String) From {
            "Apple",
            "Banana",
            "Orange",
            "Mango",
            "Grape",
            "Pineapple",
            "Peach",
            "Cherry",
            "Kiwi",
            "Strawberry"
        }

        ' Number of random items to select.
        Dim numberToSelect As Integer = 3

        Try

            ' Get random items.
            Dim selectedItems As List(Of String) =
                GetRandomElements(fruits, numberToSelect)

            Console.WriteLine("Original List:")
            For Each fruit In fruits
                Console.WriteLine($"  {fruit}")
            Next

            Console.WriteLine()
            Console.WriteLine($"Randomly Selected {numberToSelect} Items:")

            For Each item In selectedItems
                Console.WriteLine($"  {item}")
            Next

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

    End Sub

    ''' <summary>
    ''' Returns N unique random elements from a list.
    ''' </summary>
    ''' <typeparam name="T">The type stored in the list.</typeparam>
    ''' <param name="source">Source list.</param>
    ''' <param name="count">Number of elements to select.</param>
    ''' <returns>A list containing randomly selected elements.</returns>
    Private Function GetRandomElements(Of T)(
		source As List(Of T),
		count As Integer) As List(Of T)

		If source Is Nothing Then
			Throw New ArgumentNullException("source")
		End If

		If count < 0 OrElse count > source.Count Then
			Throw New ArgumentException(
				"Count must be between 0 and the number of items in the list.")
		End If

		Dim shuffled As New List(Of T)(source)

		' Fisher-Yates Shuffle
		Dim rnd As New Random()

		For i As Integer = shuffled.Count - 1 To 1 Step -1
			Dim j As Integer = rnd.Next(i + 1)

			Dim temp As T = shuffled(i)
			shuffled(i) = shuffled(j)
			shuffled(j) = temp
		Next

		' Return the first N items
		Return shuffled.GetRange(0, count)

	End Function

End Module


' run:
'
' Original List:
'   Apple
'   Banana
'   Orange
'   Mango
'   Grape
'   Pineapple
'   Peach
'   Cherry
'   Kiwi
'   Strawberry
' 
' Randomly Selected 3 Items:
'   Mango
'   Kiwi
'   Peach
'

 



answered Oct 9 by avibootz
...