Click here to Skip to main content
12,077,333 members (47,226 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

2.8K views
1 bookmarked
Posted

ForEach extension on IList

, 5 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Why limit it to IList, instead of IEnumerable?public static class ListExtension{// This is unnecessary as any collection that implement IList will also implement IEnumerable// public static void ForEach(this IList list, Action function)// {// foreach (T...
Why limit it to IList, instead of IEnumerable?

public static class ListExtension
{
//    This is unnecessary as any collection that implement IList will also implement IEnumerable
//    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);
        }
    }
}

---

I believe that the reason it is not an IEnumerable extension is they did not want operations that could mutate data as part of the library, and there was not enough benefit to justify, it is simple enough to write your own.

---

Also (in response to #2) using the extensions, makes it semantically clearer.

var studentList = new List<student>();
 
foreach (var st in studentList.Where(st => st.Age != 0))
{
    st.AgeInMonths = DateTime.Now.Subtract(st.DOB).TotalDays / 30)
}
or
studentList.Where(st => st.Age != 0)
           .ForEach(st =>{ st.AgeInMonths = DateTime.Now.Subtract(st.DOB).TotalDays / 30); });

License

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

Share

About the Author

brad.ford@cudl.com
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160212.1 | Last Updated 5 Oct 2011
Article Copyright 2011 by brad.ford@cudl.com
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid