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

ForEach extension on IList

5.00/5 (2 votes)
2 Oct 2011CPOL 25.8K  
The List class already has a method doing the same job as:public static void ForEach(this IList list, Action function)More about the ForEach method is available here. Here is the reflected ForEach method:public void ForEach(Action action){ if (action == null) { ...

The List<t> class already has a method doing the same job as:


C#
public static void ForEach<t>(this IList<t> list, Action<t> function)

More about the ForEach method is available here. Here is the reflected ForEach method:


C#
public void ForEach(Action<T> action)
{
  if (action == null)
  {
    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  }
  for (int i = 0; i < this._size; i++)
  {
    action(this._items[i]);
  }
}

to show the inner implementation of .NET ForEach() of List<t>. So we can use this .NET built in ForEach method to do the job, for example, if we want to process List<t> elements, we can try:


C#
List<string> myList = new List<string>() { "One", "Two" };
myList.ForEach(item => Console.WriteLine(item));

and with the Where clause:


C#
myList.Where(item => item == "One").ToList().ForEach(item => Console.WriteLine(item));

From the above code, we can see the Where clause will return an IEnumerable<t> object, so we cast it to List<t> using ToList() and then apply the ForEach method over it.


And also over IList<t> elements:


C#
IList<string> myList = new List<string>() { "One", "Two" };
myList.ToList().ForEach(item => Console.WriteLine(item));
myList.Where(item => item == "One").ToList().ForEach(item => Console.WriteLine(item));

License

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