Click here to Skip to main content
15,878,959 members
Articles / Programming Languages / C#
Tip/Trick

Some Extensions for IEnumerable

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
21 Dec 2010CPOL2 min read 15.3K   4   1
This tip gives a few extension methods that could be helpful and also provides a few tips about extension methods
Fluent extensions in C# is a very useful way to "add" new methods to existing classes (like System.String, etc.) instead of creating new types. Even though there is an argument that extension methods make programs less readable, they are useful to say the least. Following is an extension for IEnumerable<T> class (T type constraint is IEnumerable<TObj>). This extension takes in an IEnumerable<T> and an action to invoke with each item in T. Two constraints are used in the extensions. In the first extension, the action is not constrained and in the second extension method, both the paramters are constrained.
First is to create an interface that would be used as the type constraint's parameters.

public interface IInvokableObject
{
    void Print();
}


Following is the static class that implements the fluent extensions. Few important things to note are:
* "this" keyword is used to mark which class is being extended
* The fluent methods should be part of a static class
* The class cannot be type constrained as it's static, so the methods are type constrained for these fluent extensions.
* Thus in C# even methods could be type constrained

[Links are given below at the end of the tip, in case you are not aware of any of these concepts.]

    public static class ListInvokeExtensions
    {
        public static void InvokeAction<T>(this T t,                 
Action<IInvokableObject> action)
            where T : IEnumerable<IInvokableObject>
        {
            foreach (IInvokableObject item in t)
                action(item);
        }
        public static void InvokeActionNew<T, U>(this T t, Action<U> action)
            where T : IEnumerable<U>
            where U : IInvokableObject
        {
            foreach (U item in t)
                action(item);
        }
    }


Following is an example of how this could be used. You could create your own interface and use it in the above example. This is a very trivial example to use the extensions created above.

First, I create a type that implements the IInvokableObject interface:

public class InvokableObject : IInvokableObject
{
    public int IntData { get; set; }
    public string StrData { get; set; }
    public void Print()
    {
        Console.WriteLine(string.Format("Number is {0} and String is {1}",IntData,StrData));
    }
}


Now I am creating an IEnumerable list of InvokableObject and an action to be invoked upon each of the InvokableObject in that list:

public class ListInvokeTest
{
    public static void Main(string[] args)
    {
        Action<IInvokableObject> action = obj => obj.Print();

        Func<int,string,InvokableObject> makeobject = (number, str) => new InvokableObject() { IntData = number, StrData = str };

        List<IInvokableObject> list = new List<IInvokableObject>();
        list.Add(makeobject(1, "one"));
        list.Add(makeobject(2, "two"));
        list.Add(makeobject(3, "three"));
        list.Add(makeobject(4, "four"));
        list.Add(makeobject(5, "five"));

        list.InvokeAction(action);
        Console.WriteLine();

        list.InvokeActionNew(action);
        Console.WriteLine();
    }
}


Some important/related links are given below:

Constraints on type paramters - http://msdn.microsoft.com/en-us/library/d5x73970.aspx[^]
Fluent extensions - http://msdn.microsoft.com/en-us/library/bb383977.aspx[^]
Action<T> - http://msdn.microsoft.com/en-us/library/018hxwa8.aspx[^]
Func<T,TResult> - http://msdn.microsoft.com/en-us/library/bb549151.aspx[^]

P.S. - If anything can be improved or if you find any mistakes, please comment and let me know!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Just another passionate software developer!

Some of the contributions to the open source world - a blog engine written in MVC 4 - sBlog.Net. Check it out here. For the codeproject article regarding sBlog.Net click here!

(Figuring out this section!)

Comments and Discussions

 
GeneralReason for my vote of 3 See alternative 1 Pin
Trellium27-Dec-10 9:10
Trellium27-Dec-10 9:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.