65.9K
CodeProject is changing. Read more.
Home

ForEach extension on IList

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Sep 21, 2011

CPOL
viewsIcon

38816

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:

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:

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);
        }
    }
}