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

ForEach extension on IList

, 2 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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);
        }
    }
}

License

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

About the Author

kris444

India India
No Biography provided

Comments and Discussions

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

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
Web02 | 2.8.140721.1 | Last Updated 2 Oct 2011
Article Copyright 2011 by kris444
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid