Loop through Multiple List of objects and run a Sub

Hobbyist_programmer 621 Reputation points
2021-10-25T08:55:28.177+00:00

Hallo,

I have multiple List of Objects for eg.

List1 As New List of (xx)
List2 As New List of (xx)
List3 As New List of (xx)
.
.
.
etc

All object has a Public sub called Reset. Which clears user entered values of the property and set the object to its default values.

I want to run this sub on all list. Currently i have a following code which works but i wanted to know if i can simplify by keeping list as variable. or any alternative way to set the list of objects to its default state?

Current code
where condition is same for all list . i just want to change the list.

List1.Where(Function(x) x......).ToList.ForEach(Sub(c) c.Reset())
List2.Where(Function(x) x......).ToList.ForEach(Sub(c) c.Reset())
List3.Where(Function(x) x......).ToList.ForEach(Sub(c) c.Reset())
.
.

Any ideas? thanks.

Developer technologies VB
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-10-25T09:40:46.773+00:00

    If all of the lists consist of objects of the same type (xx) and the condition is the same, then you can define a Sub:

    Sub Reset(list As List(Of xx))
    
        For Each x In list.Where(Function ...)
            x.Reset()
        Next
    
    End Sub
    

    Usage:

    Reset(List1)
    Reset(List2)
    Reset(List3)
    

    You can also consider this:

    List1.Concat(List2).Concat(List3).Where(Function ...).All(Function(x)
                                                                        x.Reset()
                                                                        Return True
                                                                    End Function)
    

  2. Xingyu Zhao-MSFT 5,381 Reputation points
    2021-10-26T02:46:16.743+00:00

    Hi @Hobbyist_programmer ,
    You can define an extension method like:

    Module ExtensionOperation  
        <Extension()>  
        Sub Reset(Of T)(ByVal lst As List(Of T), ByVal provider As Func(Of T, Boolean))  
            lst.Where(Function(x) provider(x)).ToList().ForEach(Function(c) c.GetType().GetMethod("Reset").Invoke(c, Nothing))  
        End Sub  
    End Module  
    

    Usage:

            List1.Reset(Function(x) ...)  
            List2.Reset(Function(x) ...)  
    

    Hope it could be helpful.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.