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);
}
}
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.