Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

ForEach extension on IList

4.00/5 (1 vote)
2 Oct 2011CPOL 38.8K  
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)