Click here to Skip to main content
16,018,805 members
Articles / Programming Languages / C#
Tip/Trick

ForEach extension on IList

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
2 Oct 2011CPOL 38.7K   1
ForEach extension for the IList

Very often, we have the requirement to perform some sort of action on each entity in a List. For example, from a student list, I need to update the Age of the student whose Age is 0.


I can do it like this:


C#
var studentList = new List<student>();

studentList.Where<student>(s => s.Age == 0).ForEach<student>(
  st => st.AgeInMonths = DateTime.Now.Subtract(st.DOB).TotalDays / 30);

For this to work, these are the extension methods needed:


C#
public static class ListExtension
{
    public static void ForEach<t>(this IList<t> list, Action<t> function)
    {
        foreach (T item in list)
        {
            function(item);
        }
    }

    public static void ForEach<t>(this IEnumerable<t> list, Action<t> function)
    {
        foreach (T item in list)
        {
            function(item);
        }
    }
}

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralIList<T> implements IEnumerable<T>, so you don't need the IL... Pin
Richard Deeming3-Oct-11 9:33
mveRichard Deeming3-Oct-11 9:33 

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.