Friday 7 September 2012

Beginning .Net , C# Tips : Create Custom LINQ Extension Methods with C# Examples

There is a need to create a custom LINQ extension method in .Net Application. This is a very good .Net Framework feature. These extension methods are very handy in software development.
For that we need to create Static Class and Static Methods.

Here is example for this.
In this example we create one static class "LINQExtensions" and create one static method "GetTopTwo" in this class. This Method return type "IEnumerable<string>". This Method get get top two values in given list.
We implement this in String Array and Generic List object.

C# Examples :
static class LINQExtensions
{
    public static IEnumerable<string> GetTopTwo(
    this IEnumerable<string> source)
    {
        return source.Take(2);
    }
}
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] strArray = { "C#", ".Net", "Java", "PHP" };
        IList<string> Lst = new List<string> { ".Net", "Java", "C#", "PHP" };
        
        IEnumerable<string> IEResult1 = strArray.GetTopTwo();
        Response.Write("<br/><b>String Array:</b><br/> ");
        foreach (string element in IEResult1)
        {
            Response.Write("<br/>" + element);
        }

        Response.Write("<br/>");

        IEnumerable<string> IEResult2 = Lst.GetTopTwo();
        Response.Write("<br/><b>Generic List:</b><br/> ");
        foreach (string element in IEResult2)
        {
            Response.Write("<br/>" + element);
        }
    }


Output :


View More LINQ Examples. Click Here... 

For Beginning .Net articles. Click Here...

This type of C# Tips is very useful in day to day programming life.

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