Thursday 13 September 2012

Beginning .Net , C# Tips : Create Custom LINQ Extension Methods in VB.Net

Click Here to Download Sample CreateCustomLINQExtensionMethod.zip

You can create your own custom LINQ extension method in .Net Application. These extension methods are very handy in software development. Creating a LINQ extension method in VB.Net has Different approach than C#.Net . For that we need to create "Module" and in this Module we create a methods and add this "<Runtime.CompilerServices.Extension()>" attribute to this methods.

Here is example for this.
In this example we create one Module "LINQExtensions" and create one public method "GetTopTwo" in this Module. This Method return type "IEnumerable(Of String)". This Method get top two values in given list. We implement this in String Array and Generic List object.



VB.Net Examples :
Public Module LINQExtensions

    <Runtime.CompilerServices.Extension()> _
    Public Function GetTopTwo(ByVal source As IEnumerable(Of String)) As IEnumerable(Of String)
        Return source.Take(2)
    End Function

End Module

        Dim strArray As String() = {"C#", ".Net", "Java", "PHP"}

        Dim objArrayIEResult As IEnumerable(Of String) = strArray.GetTopTwo()

        Response.Write("<br/><b>String Array:</b><br/> ")
        For Each element As String In objArrayIEResult
            Response.Write("<br/>" & element)
        Next

        Response.Write("<br/>")


        Dim Lst As IList(Of String) = New List(Of String)() From { _
         ".Net", _
         "Java", _
         "C#", _
         "PHP" _
        }
        Dim objListIEResult As IEnumerable(Of String) = Lst.GetTopTwo()

        Response.Write("<br/><b>Generic List:</b><br/> ")

        For Each element As String In objListIEResult
            Response.Write("<br/>" & element)
        Next

Output :



View More LINQ Examples. Click Here... 

For Beginning .Net articles. Click Here...

Click here to view useful  C# Tips .

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment