Click here to Skip to main content
Click here to Skip to main content

Some Extensions for IEnumerable

By , 21 Dec 2010
Rate this:
Please Sign up or sign in to vote.
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)

About the Author

Karthik. A
Software Developer
United States United States
Just another passionate software developer! I recently acquired my MCTS Wink | ;)
 
My latest contribution to the open source world is a blog engine written in MVC 3 - sBlog.Net. Check it out here. For the codeproject article regarding sBlog.Net click here!
 
I have recently (re)launched my web-site. Check it out at http://thekfactor.info!

Eventually, I have a blog under my own sub-domain. It is http://blog.thekfactor.info

Also check out my latest app - directory comparer [codeproject article and dedicated site] and my latest jquery plugin - partial collapsible panel!!!


All sites were developed in ASP.Net MVC 2 Smile | :)

Follow on   Twitter

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 21 Dec 2010
Article Copyright 2010 by Karthik. A
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid