IEnumerable Aggregate, Accumulator Function in VisualBasic.Net

I like Generics so much because it saves a lot of my time.

The following code example demonstrates how to use IEnumerable Aggregate and build some useful functions.

Example No. (1): May be used to calculate the totals of integers


     Public Shared Function AcumulateIntegers(source As IEnumerable(Of Integer)) As Integer
        Return source.Aggregate(New Func(Of Integer, Integer, Integer)(AddressOf AddInteger))
    End Function

    Private Shared Function AddInteger(a As Integer, b As Integer) As Integer
        Return (a + b)
    End Function

Usage:

 Dim total As Integer = AcumulateIntegers(New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8})

Example No. (2): Might used to union some rectangles


    Public Shared Function UnionRectangles(source As IEnumerable(Of Rectangle)) As Rectangle
        Return source.Aggregate(New Func(Of Rectangle, Rectangle, Rectangle)(AddressOf Rectangle.Union))
    End Function

Usage:


        Dim rectA As Rectangle = New Rectangle(0, 0, 20, 20)
        Dim rectB As Rectangle = New Rectangle(0, 0, 20, 20)
        Dim rectC As Rectangle = New Rectangle(0, 0, 20, 20)
        Dim rectD As Rectangle = New Rectangle(0, 0, 20, 20)
        Dim rectE As Rectangle = New Rectangle(0, 0, 20, 20)

        Dim rect As Rectangle = UnionRectangles(New List(Of Rectangle) From {rectA, rectB, rectC, rectD, rectE})


Additional usage, the following code example demonstrates how to use it based on MSDN.

Example No. (2): Alternative


    Public Shared Function UnionRectangles(source As IEnumerable(Of Rectangle)) As Rectangle
        Return source.Aggregate(New Func(Of Rectangle, Rectangle, Rectangle)(AddressOf AccumalateRectangles))
    End Function

    Private Shared Function AccumalateRectangles(rect1 As Rectangle, rect2 As Rectangle) As Rectangle
        Return Rectangle.Union(rect1, rect2)
    End Function

Usage:

 same usage as demonstrated in Example 2

Example No. (3): May be used to reverse a sentence


    ' Refer To
    ' http://msdn.microsoft.com/en-us/library/vstudio/bb548651%28v=vs.100%29.aspx
    '''
    ''' Reverse a String of words.
    '''

    '''
    '''
    '''
    Public Shared Function ReverseSentence(sentence As String) As String
        Dim strings() As String = sentence.Split(" "c)
        ' Prepend each word to the beginning of the new sentence to reverse the word order and
        ' get the output
        Return strings.Aggregate(Function(current, word) word & " " & current)
    End Function


Usage: 

    Dim txt As String = ReverseSentence("IEnumerable Aggreagte Test")
    Me.Text = txt


Really Generics Rock....Enjoy it

Comments

Popular posts from this blog

مقدمة الي تشفير الحروف الأبجدية العربية

VB.NET Translucent Control using GDI+

Add Custom Event to a Class in VB.NET